.NET Applications with Unmanaged DLLs

C# becomes increasingly popular for implementing Windows GUIs as .NET applications. However a lot of the business logic and communication modules are still implemented in C++ native (i.e. unmanaged) DLLs. There are several ways of accessing the C++ unmanaged business logic from the C# managed user interface, based on P/Invoke or COM.

After successfully using such a managed/unmanaged application on a 32 bit OS starting it on a 64 bit OS brings a surprise: the application fails to start. The reason is that a .NET application built with default settings is executed as a 64 bit application. Whether an application is running as 32 or 64 bit is visible in the task manager; all 32 bit processes are marked by appending '* 32' to the process image name dotnet task mngr 32bit

The problem arises when this application accesses the unmanaged 32 bit DLL. Everything is ok again, if the application is marked as a 32 bit application by setting the flag '32BIT' in the program executable header. This tells a 64 bit Windows® OS to execute the application with the WoW64 layer.

There are two ways of achieving this:

1. change the target type in the 'Build' settings of the Visual Studio® project from 'Any CPU' to 'x86'

dotnet project settings target cpu

 2. set the flag '32BIT' in the binary file using the corflags tool

The tool 'corflags.exe' is installed with Visual Studio® or the Windows® SDK. It can be started from the command prompt. Starting it with the application name as the only parameter shows the current setting of the flags.

dotnet 32bit dll corflags def

By adding the parameters /32BIT+ and /ILONLY-, we toggle the state of both relevant flags.

dotnet 32bit dll corflags fix

Setting only the '32BIT' flag would be sufficient, but by also clearing the ILONLY flag we indicate the use of unmanaged code.