Change C# Dllimport Target Code Depending on X64/X86

Change C# DllImport target code depending on x64/x86

This is primarily a deployment problem, just have your installer copy the right DLL based on the Windows version on the target machine.

But nobody ever likes to do that. Dynamically pinvoking the correct DLL's function is enormously painfully, you have to write delegate types for every exported function and use LoadLibrary + GetProcAddress + Marshal.GetDelegateForFunctionPointer to create the delegate object.

But nobody ever likes to do that. The less painful tack is to declare the function twice, giving it different names and using the EntryPoint property in the [DllImport] attribute to specify the real name. Then test at runtime which you want to call.

But nobody ever likes to do that. The most effective trick is steer Windows into loading the correct DLL for you. First thing you have to do is copy the DLL into a directory where Windows will not look for it. Best way is to create an "x86" and an "x64" subdirectory in your build directory and copy the appropriate DLL into each. Do so by writing a post-build event that creates the directories and copies the DLLs.

Then tell Windows about it by pinvoking SetDllDirectory(). The path you specify will be added to the directories that Windows searches for a DLL. Like this:

using System;
using System.Runtime.InteropServices;
using System.Reflection;
using System.IO;

class Program {
static void Main(string[] args) {
var path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
path = Path.Combine(path, IntPtr.Size == 8 ? "x64" : "x86");
bool ok = SetDllDirectory(path);
if (!ok) throw new System.ComponentModel.Win32Exception();
//etc..
}
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool SetDllDirectory(string path);
}

Do consider if having the code run in 64-bit mode is actually useful to you. It is pretty rare to need the giant virtual memory address space you get from it, the only real benefit. You still need to support the 32-bit version that needs to operate correctly in the 2 gigabyte case.

Target 32 Bit or 64 Bit native DLL depending on environment

Here is the solution I've used on many projects:

  • name the 32-bit assembly with a "32-bit oriented name". For
    example MyAssembly.Native.x86.dll
  • name the 64-bit assembly with a "64-bit oriented name". For example MyAssembly.Native.x64.dll
  • compile the managed assembly as 'Any Cpu'
  • ship everything in the same path

Here is how I declare P/Invoke methods:

[DllImport("MyAssembly.Native.x86.dll", EntryPoint = "MyTest")]
private static extern void MyTest86(MyType myArg);

[DllImport("MyAssembly.Native.x64.dll", EntryPoint = "MyTest")]
private static extern void MyTest64(MyType myArg);

And here is the corresponding 'MyTest' function which is the one I'll always use (the others are here just for correct bitness binding). It has the same signature than the other P/Invoke ones:

public static void MyTest(MyType myArg)
{
if (IntPtr.Size == 8)
{
MyTest64(myArg);
return;
}

MyTest86(myArg);
}

The advantages are:

  • you can ship all binaries (DLLs, EXEs, ...) in the same path
  • you support 32-bit and 64-bit processes and OSes with the same file layout
  • you don't have to resort to Win32 apis for changing dll load path

The inconveniences are:

  • you'll have 3 method declarations for 1 'real' method
  • you'll loose some CPU cycles because of the bitness test
  • depending on your context, sometimes you can't change the native DLLs names, so you just can't do this

Load x64 or a x86 DLL depending upon the platform?

If we are talking about unmanaged DLLs, declare the p/invokes like this:

[DllImport("DllName.dll")]
static extern foo();

Note that we are not specifying a path to the DLL, just its name, which I presume is the same for both 32 and 64 bit versions.

Then, before you call any of your p/invokes, load the library into your process. Do that by p/invoking to the LoadLibrary API function. At this point you will determine whether your process is 32 or 64 bit and build the full path to the DLL accordingly. That full path is what you pass to LoadLibrary.

Now, when you call your p/invokes for the library, they will be resolved by the module that you have just loaded.

For managed assemblies then you can use Assembly.LoadFile to specify the path of the assembly. This can be a little tricky to orchestrate, but this excellent article shows you how: Automatically Choose 32 or 64 Bit Mixed Mode DLLs. There are a lot of details relating to mixed mode and the native DLL dependencies that are probably not relevant to you. The key is the AppDomain.CurrentDomain.AssemblyResolve event handler.

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

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.


Related Topics



Leave a reply



Submit