Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

p/invoke a 32-bit dll from a C# program running on an x64 machine

Tags:

c++

c#

pinvoke

I have a C# program that I compile with all of the default settings on an x64 computer.

I want to p/invoke a DLL which I know is a 32-bit (unmanaged) C++ DLL.

I can get this to work when my C# program runs on a 32-bit machine, but not a 64-bit machine.

How can I specify in the DllImport call that I am calling into a 32-bit dll?

Example of what I have now:

[DllImport("test32bitdll.dll", SetLastError=true)]
public static extern void MyFunc();

I do not have the source code of the test32bitdll.dll file.

like image 779
Net Citizen Avatar asked Jun 23 '10 17:06

Net Citizen


2 Answers

Running 32-bit unmanaged code in a 64-bit process is not possible. Or the reverse. The options you have available:

  • Force the EXE to run in x86 mode with the Target Platform setting in the Build tab
  • Recompile the C++ DLL in x64 mode. That's often possible without too many hassles, provided you have the source code and not a dependency on some 3rd party code that is only available in 32-bits
  • Run the C++ DLL in a surrogate process that is forced to run in 32-bit mode. You'll need to use an interprocess communication mechanism to get your 64-bit process to talk to the 32-bit surrogate. Named pipes, sockets, .NET Remoting, WCF are typical choices in .NET.

The 3rd option can give you the most bang for your buck but it can be slow if there's a lot of data exchanged and tends to be fragile. It can be difficult to deal with failure of the surrogate process.

like image 61
Hans Passant Avatar answered Nov 14 '22 23:11

Hans Passant


The easiest way to get this working is change your exe to build for "x86 only".

like image 29
Stephen Cleary Avatar answered Nov 14 '22 22:11

Stephen Cleary