Jul 21, 2011

BadImageFormatException When 64 meets 32

What the Exception Said

It said "BadImageFormatException" Obvious right? Nice clear use of the term "Image" as you go off looking for a bad. jpg, .png. or gif file.

What the Exception Should Have said

Expected64BitDllGot32BitDllException – OK you can probably get a BadImageFormatException for other reasons, but every time I've seen it, this is why.

When Any CPU Doesn't Help

SNAGHTML5f60f5If you stick to the managed world of C# you'll probably never see this exception. If you write a .DLL in C++/CLI with common language runtime support set to /clr (under Project Properties as shown in the image), you'll almost certainly see it.

SNAGHTML528650I was wrapping an unmanaged C++ DLL in a managed /clr wrapper when I ran across it. What happens is that the compiler will create either a 64 bit or 32 bit version of your .DLL. The advanced linker settings as shown in the image allow you to set the target machine.

When Worlds Collide

The problem occurs when you host the .DLL in a managed application that supports Any CPU (or specifically a 64 bit model). If you test on a 32 bit machine you won't see a problem. Your hosting managed application will run in 32 bit mode and it will load the 32 bit .DLL without issue. When you run on a 64 bit platform your hosting application will run in 64 bit mode and when it goes to load the DLL (remember it's dynamically linked) it will throw the BadFormatImageException  because it can't find a 64 bit version of the .DLL.

One Love One Heart

SNAGHTML5acb5bThe easy solution is to have one world. Use the properties dialog of your managed application as shown in the image and force the hosting application to be 32 bit. Since 32 bit applications will run on a 64 bit machine under WOW your problem will be solved. If for performance reasons you want to have your application run in 64 bit mode under 64 bit machines, I suspect you will have to build your .DLL twice. Once for each target machine. I've never done this but I suspect you just create distribution folders with the proper .DLL and it will work.

About Me

My photo
Tod Gentille (@todgentille) is now a Curriculum Director for Pluralsight. He's been programming professionally since well before you were born and was a software consultant for most of his career. He's also a father, husband, drummer, and windsurfer. He wants to be a guitar player but he just hasn't got the chops for it.