Using a 32bit or 64bit dll in C# DllImport

I’ve found the simplest way to do this is to import the two methods with different names, and calling the right one. The DLL won’t be loaded until the call is made so it’s fine:

[DllImport("MyDll32.dll", EntryPoint = "Func1", CallingConvention = CallingConvention.Cdecl)]
private static extern int Func1_32(int var1, int var2);

[DllImport("MyDll64.dll", EntryPoint = "Func1", CallingConvention = CallingConvention.Cdecl)]
private static extern int Func1_64(int var1, int var2);

public static int Func1(int var1, int var2) {
    return IntPtr.Size == 8 /* 64bit */ ? Func1_64(var1, var2) : Func1_32(var1, var2);
}

Of course, if you have many imports, this can be become quite cumbersome to maintain manually.

Leave a Comment