Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

.net

pinvoke

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?

like image 206
Eric Avatar asked Apr 13 '10 19:04

Eric


2 Answers

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.

like image 157
Reed Copsey Avatar answered Oct 05 '22 08:10

Reed Copsey


You'll have no trouble if the DLL whose export you P/Invoke is also available in a 64-bit version. Which is definitely the case for the Windows DLLs, like kernel32.dll. GetPrivateProfileString() will work just as well, you don't need to make the [DllImport] attribute any different. Assuming you used IntPtr where required.

Odds get lower when you use a 3rd party DLL or a COM server that is outdated or not included with Windows. You'll find out quickly if the x86 Target platform override is required, the runtime exception is loud enough. You'll get a BadImageFormat exception for pinvoked DLLs, 32-bit COM servers produce a "Class Not Registered" exception.

like image 26
Hans Passant Avatar answered Oct 05 '22 08:10

Hans Passant