Monday, 19 April 2010

Compiling .Net for a Specific Target Platform (Any CPU vs x86 vs x64)

Given my new dev machine runs Windows XP x64 (64 bit OS), I've been considering the implications of compiling the assemblies and executables for different target CPUs.

First of all, no matter what target CPU you select, the .Net compiler STILL compiles the source to the Common Intermidate Language (CIL). The executable or assembly being compiled is only affected by this setting to set the platform status information on the assembly’s Common Language Runtime (CLR) header. The CIL is only turned into native code by the CLR at runtime using the Just-in-time (JIT) compiler.

Now here's the important bits, so pay attention...

32 Bit Machine

  • Any-CPU executable will run as a 32 bit process, can load Any-CPU.dll and x86.dll but will get BadImageFormatException if it tries to load x64.dll.
  • x86 executable will run as a 32 bit process. It can load Any-CPU.dll and x86.dll but will get BadImageFormatException if it tries to load x64.dll.
  • x64 executable will not load. The framework will throw a BadImageFormatException if ran.

64 Bit Machine

  • Any-CPU executable will run as a 64 bit process. It can load Any-CPU.dll and x64.dll but will get BadImageFormatException if it tries to load x86.dll.
  • x86 executable will run as a 32 bit process (WOW64). It can load Any-CPU.dll and x86.dll but x64.dll will not load, the framework will throw a BadImageFormatException.
  • x64 executable will run as a 64 bit process. It can load Any-CPU.dll and x64.dll but x86.dll will not load, the framework will throw a BadImageFormatException.
Rule of thumb is... by limiting the CPU target at compilation you would be saying there is something being used by the assembly (something likely unmanaged) that requires 32 bits or 64 bits.

1 comment:

  1. An Any CPU set up will JIT to 64 bit rule when packed into 64 bit procedure and 32 bit when packed into a 32 bit procedure.

    ReplyDelete