使用C#中的DllImport一个32位或64位的DLLDllImport、DLL

2023-09-02 12:00:57 作者:EXIST

这里的情况是,我使用的是基于C的DLL我dot.net的应用程序。有2个DLL文件,一个是32位叫MyDll32.dll,另一种是被称为MyDll64.dll一个64位版本。

Here is the situation, I'm using a C based dll in my dot.net application. There are 2 dlls, one is 32bit called MyDll32.dll and the other is a 64bit version called MyDll64.dll.

有一个静态变量持有的DLL文件名:字符串DLL_FILE_NAME

There is a static variable holding the DLL file name: string DLL_FILE_NAME.

和它用于以下列方式:

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

简单为止。

正如你可以想像,软件编译任何CPU打开。

As you can imagine, the software is compiled with "Any CPU" turned on.

我也有以下的code,以确定系统应使用64位文件或32位的文件。

I also have the following code to determine if the system should use the 64bit file or the 32bit file.

#if WIN64
        public const string DLL_FILE_NAME = "MyDll64.dll";
#else
        public const string DLL_FILE_NAME = "MyDll32.dll";        
#endif

现在,你应该按照执行上下文看.. DLL_FILE_NAME是定义在编译时间,而不是在执行时间,所以未加载正确的DLL的问题。

By now you should see the problem.. DLL_FILE_NAME is defined in compilation time and not in execution time so the right dll isn't loaded according to the execution context.

什么是处理这个问题的正确方法是什么?我不想两种执行文件(一个用于32位,另一个用于64位)?如何设置DLL_FILE_NAME的在的它采用的是的DllImport声明?

What would be the correct way to deal with this issue? I do not want two execution files (one for 32bit and the other for 64bit)? How can I set DLL_FILE_NAME before it is used in the DllImport statement?

推荐答案

我发现这样做最简单的方法是导入这两种方法有不同的名称,并调用正确的。该DLL将不会被载入直到呼叫是由这样它的罚款:

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.

 
精彩推荐
图片推荐