Tuesday, October 14, 2008

Running 32 bit .Net applications on a 64 bit machine

Just been having a problem trying to get a .Net application running on my 64bit Vista machine.  The app was compiled using the "Any CPU" flag, which means that it can target both 32 or 64 bit machines.  With this flag set, the .Net bootstrap process loads up the appropriate CLR based upon your machine architecture - if you're running a 32 bit OS, then the 32 bit CLR is loaded and the JIT compiler generates 32 bit code.  If you're running a 64 bit OS, then you can guess what happens - 64 bit CLR and 64 bit code.

For most apps, this is probably exactly the behaviour that you want (although do remember that you need to test on both environments).  If there is a reason why you need to target a specific architecture, then you can change the build settings to force either 32 or 64 bit.  Why would you want to force things?  A good reason would be if you are loading up 32 bit native DLLs for some reason (perhaps your database vendor only ships 32 bit client DLLs, for example).  In this case, quite clearly you need to make sure that your app is also running 32 bit - if not, then when launched on a 64 bit OS, it'll throw a BadImageFormatException at the point that it tries to load the native DLL. 

That's all fine, but what if you've been given an app that needs to run in 32 bit mode, but was compiled with the "Any CPU" flag?  If you've got the code then you could recompile, but what if that's not an option?  Turns out that there's a handy tool called corflags.exe which comes with the SDK.  Using this, you can flip the 32 bit flag in the application without requiring access to the source.  For example:

corflags /32BIT+ /Force TheApplication.exe

the /Force flag is needed if the application is strong name signed - if you omit that flag, then it will fail when run against such assemblies.  Obviously, once the bit has been flipped the strong name is no longer valid.  If you've got access to the private key then you can re-sign.  If you don't have the private key and you need to keep the strong name then I'm afraid you're out of luck.

1 comment:

Anonymous said...

Thanks for sharing!