BadImageFormatException when loading 32 bit DLL, target is x86

Coder picture Coder · Apr 28, 2010 · Viewed 68k times · Source

I have a DLL (FreeType) which is certainly 32-bit (header: IMAGE_FILE_MACHINE_I386).

I want to use it from C# code, using DllImport.

Target of my application is x86, IntPtr.Size is 4, process is 32-bit.

But I get BadImageFormatException (Exception from HRESULT: 0x8007000B). What can be wrong?

Of course I use 64-bit Windows 7.

Answer

Eric Smith picture Eric Smith · Apr 28, 2010

From what I understand, an assembly specifically built for x86 and running in a 64-bit operating system can only load libraries built for x86 or a BadImageFormatException will be thrown. In a 64-bit OS, an assembly built for Any CPU or x64 will throw the same exception when trying to load an x86 library.

So, assuming nothing incredibly weird is going on, I would ensure that you've set your application to build as x86 by opening the project properties and clicking on the Build tab. Ensure 'Platform Target' is set as 'x86' and not Any CPU.

Alternatively, you could try to find a 64-bit version of the DLL for testing purposes.