Mixing 32-bit and 64-bit P/Invokes
I've run into a problem that I'm pretty sure I know the answer to, but I figured I'd at least ask and see if there was some "magic bullet" that might save me a huge headache.
Here's the high-level view.
I have a managed application. This application interfaces with hardware via third-party libraries from different vendors. I have full control over the consuming managed app and zero control over the hardware API libraries.
Vendor A provides only a 32-bit native SDK. To allow us to use it on 64-bit systems, we marked the application to run in 32-bit mode. All was well.
We are now integrating with Vendor B, which provides 64-bit-specific native API libraries on 64-bit machines. The 32-bit native DLL from Vendor B will not work on a 64-bit system (tried that). If I build a test harness running as 64-bit or AnyCPU, it works fine. If I mark it as 32-bit, it fails on the P/Invoke calls.
It seems that Vendor A and Vendor B hardware are开发者_高级运维 going to be mutually exclusive on 64-bit PCs, but I'm wondering if anyone has suggestions on how to possibly work around that.
The problem is not a .NET or P/Invoke. It is an OS issue. A 64-bit process can only load 64-bit DLLs. A 32-bit process can only load 32-bit DLLs. The magical Windows-on-Windows (or WoW) layer that lets 32-bit apps run on 64-bit Windows exists between the user-mode process (EXE and DLLs) and the kernel. There is no way to run a 32-bit DLL inside a 64-bit process. The WoW layer exists below that. (Basically WoW is a 32-bit wrapper around the 64-bit Win32 API, which marshals data and function calls between the 32-bit world of the process and the 64-bit world of the operating system.)
Your best/only option is to run your 32-bit and 64-bit components in separate processes and use some form of IPC to communicate. This has the added benefit of decoupling your core application from potentially unstable 3rd-party components. If a 3rd-party component crashes or misbehaves, it's simply a matter of re-starting the process containing that component.
You can make a separate 32-bit process to interact with Vendor A, then communicate with it using WCF.
Since you can't load 32 bit and 64 bit images into the same process, you'll have to use a multi-process solution.
Hopefully someone can suggest a better alternative, but perhaps you could wrap one of the libraries (whichever one has the lowest bandwidth connection to your app) in a separate process, and then communicate with it (e.g. via sockets).
精彩评论