AnyCPU, x86 and x64 in Visual Studio

Within Visual Studio, you have the option to build your .Net application either for x32, x86 or AnyCPU. AnyCPU will allow the JIT-compiler of .Net to run the application on a 32-bits system in 32 bit and a 64-bits system in 64 modus.

Although this seems like a nice option, you will run soon in problems when compiling to third-party libraries. The third-party library can be pre-build into 32-bit or 64-bit. When you now compile your .Net application to AnyCPU against a 32-bit third-party DLL, it will give an BadImageFormat exception when running on a 64-bit system. The .Net application will, due to the AnyCPU option, run as a 64-bit application. Since the third-party library is 32-bit, this will clash.
Although you compile your application for AnyCPU, but select “Prefer 32-bit”, it again will be compiled into 32-bit when running on a 64-bit machine.

How to detect 32-bit or 64-bit in C#

You can detect if your application is running in 32-bit or 64-bit by looking at the size of a pointer. Since this pointer is platform-specific, the size of the pointer will tell your application runs on which bitness platform.When the size of the pointer is 8, your running on a 64-bit machine. When it’s size is 4, it is a 32-bit machine. With this small program you can see the difference:

 if (IntPtr.Size == 8) 
 { 
   Console.WriteLine("We're running 64-bit!"); 
 } 
 else 
 {
   if (IntPtr.Size == 4) 
   { 
      Console.WriteLine("We're running 32-bit!"); 
   }
 }
 Console.ReadLine();
}

By using this, you can also make calls you native DLL’s which have a diffent bitsize. By determing the platform, you can make the right call:

 [DllImport("mydll_32bit.dll", SetLastError = true)]
 static extern void DoStuff_32(string name);

 [DllImport("mydll_64bit.dll", SetLastError = true)]
 static extern void DoStuff_64(string name);

 if (IntPtr.Size == 8)
 { 
   DoStuff_64("Test");
 }
 else 
 {
   if (IntPtr.Size == 4)
   { 
     DoStuff_32("Test");
   }
 }

So we now calling the right version off the DLL, depending on the platform we’re running on.

Posted in Uncategorized by Bruno at September 1st, 2017.

Leave a Reply