Microsoft & .NETHow to Run Native Code in Your Azure Service

How to Run Native Code in Your Azure Service content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.


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.

Image 1


Image 2

Now, go ahead and add your native DLL to the solution.

Right click on the WebRole1 Project, select Add -> Existing Item

ge 3

Select your DLL and click OK.

Image 4

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”.

Image 5

Now, navigate to the Property Page of the WebRole and change the trust level to “Full trust” if it is not already set so.

Image 6

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.

using System.Runtime.InteropServices;

You will also need to declare the signature of the native function you want to call from the DLL.

namespace WebRole1


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

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories