Search code examples
c#c++dlldllimport

Importing x86_64 DLL in project with x86 environment through P/Invoke


My current target framework is .NET Framework v4.0.

I'm having issues importing the DLL as I get the "BadImageFormatException" similar to this post BadImageFormatException when loading 32 bit DLL, target is x86

From there I realised that the DLL (retrieved from NuGet) can only be built in x64, but my solution can only be x86 as that is what the team has decided on. So I can't change the configuration to x64.

I'm currently using P/Invoke to import it (DllImport). My machine is x64. For context, this DLL is built with managed native c++ code and I am trying to convert it to c#. I cannot touch the dll as it is not my library, but my project is in c#.

Since I am not allowed to change my project settings, and the DLL can only be built in and run in x64, is there any other way to solve this issue?


Solution

  • You can not load a 64-bit dll in a 32-bit process. Your options are:

    1. Update your application to x64 mode. This typically requires all native components to be changed to x64 versions. You said you team decided on x86, but decisions can be re-evaluated if you have good enough reasons to.
    2. Find a way to get a x86 version of your library. This might involve creating your own build, so it might be expensive.
    3. Run your library in a separate process, and use your favorite RPC/IPC method to communicate between the processes. This will typically make deploying and debugging your application at least a bit more difficult, depending on how frequently the library is used.