Search code examples
.netpinvoke

Can a .NET application targeted for "Any CPU" use P/Invoke calls in multiple environments?


I have a .NET application that uses some API calls, for example GetPrivateProfileString. So far it has always run on 32-bit machines.

In order to run on 64-bit machines, must I change the "Platform Target" to "x86"? Or is there a way to let the runtime know which API DLL to invoke depending on the runtime environment?


Solution

  • You need to make sure that you're only using P/Invoke calls against a 64bit DLL.

    One option is to move all of your "methods" into a standard interface (or abstract base class), and provide 2 implementations, one 32bit and one 64bit. You can have a factory method construct the appropriate instance of the class depending on the size of IntPtr.

    This allows an "AnyCPU" app to correctly, at runtime, determine which DLL to P/Invoke into, and does work.