Windows Azure, by default, runs code in low trust. Certain business scenarios might dictate the necessity to run code which already exists in the form of native code, e.g. C++ DLLs. Under these circumstances, it is important that the business logic which has been written and tested over a long period of time does not need to be rewritten.
Windows Azure allows the ability to run untrusted code by enabling full trust. This will allow code to run in non-admin scenarios and extends the logic to unmanaged code via P/Invoke.
Now, go ahead and add your native DLL to the solution.
Right click on the WebRole1 Project, select Add -> Existing Item
Select your DLL and click OK.
We then need to change the Visual Studio Property of the native dll as under. Make sure “Build Action” to Content and “Copy to output” to “Copy if newer”.
Now, navigate to the Property Page of the WebRole and change the trust level to “Full trust” if it is not already set so.
Now, go add and add UI around the code you want to call from the native DLL.
To call the code in the native DLL, you will need to add the following import statement in your source file for the web page.
You will also need to declare the signature of the native function you want to call from the DLL.
public partial class _Default : System.Web.UI.Page
static extern int FindTotal(int num1, int num2);
protected void Page_Load(object sender, EventArgs e)
You can now call the FindTotal method anywhere in the class just like a regular method.
Now, compile and run the application. You will find that the call to the native method is successful.
Caveat: You might hit the BadImageFormatException when you run the application. This might be because of bitness difference between the native dll and the Azure Application DLL. You can resolve this by choosing the right bitness of your DLL or your Azure project.
In this article, we learned how to run native code in a Windows Azure service. I hope you have found this information useful.
About the Author
Vipul Patel is a Software Engineer currently working at Microsoft Corporation. He is currently working in the Microsoft Lync team and has worked in the .NET team earlier in the Base Class libraries and the Debugging and Profiling team. He can be reached at firstname.lastname@example.org