Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Targeting x86 vs AnyCPU when building for 64 bit window OSes

Tags:

.net

64-bit

I have an existing C# application written for .NET 2.0 and targeting AnyCPU at the moment. It currently references some third party .NET DLLs which I don't have the source for (and I'm not sure if they were built for x86, x64 or AnyCPU).

If I want to run my application specifically on a 64 bit Windows OS, which platform should I target in order for my app to run without errors? My understanding at the moment is to target:

  • x86: If at least one third party .NET dll is built for x86 or use p/Invoke to interface with Win32 DLLs. Application will run in 32 bit mode on both 32 bit and 64 bit OSes.
  • x64: If all third party .NET dlls are already built for x64 or AnyCPU. Application will only run in 64 bit OSes.
  • AnyCPU: If all third party .NET dlls are already built for AnyCPU. Application will run in 32 bit mode on 32 bit OSes and 64 bit on 64 bit OSes.

Also, am I right to believe that while targeting AnyCPU will generate no errors when building a application referencing third party x86 .NET DLLs, the application will throw a runtime exception when it tries to load these DLLs when it runs on a 64 bit OS.

Hence, as long as one of my third party DLLs is doing p/Invoke or are x86, I can only target x86 for this application?

like image 633
anonymous Avatar asked Jun 01 '10 04:06

anonymous


1 Answers

You can do P/Invoke from an AnyCPU DLL, you just need to be a bit more careful about the P/Invoke definitions (i.e. that you're not inadvertently assuming 32-bit or something). The problem is that it's kind of hard to know if a 3rd party DLL is doing the right thing without Reflector and disassembling it (unless the developer specifically states 64-bit support of course).

But other than that, you're pretty much spot-on.

To be honest, for 99% of applications, targetting x86 is perfectly acceptable. It's a relatively small number of applications that actually benefit from being 64-bit. (Performance issues typically come out as a bit of a wash: more registers are offset by the register renaming of x86 mode and larger data structures because pointers are twice as big [and in a reference-heavy system like .NET that's even worse])

like image 71
Dean Harding Avatar answered Nov 16 '22 00:11

Dean Harding