问题描述
情况是这样,我在我的 dot.net 应用程序中使用基于 C 的 dll.有2个dll,一个是32位版本的MyDll32.dll,另一个是64位版本的MyDll64.dll.
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);
到目前为止很简单.
如您所想,该软件是在打开Any CPU"的情况下编译的.
As you can imagine, the software is compiled with "Any CPU" turned on.
我还有下面的代码来判断系统应该使用 64bit 文件还是 32bit 文件.
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 位)?如何在 DllImport 语句中使用 之前设置 DLL_FILE_NAME?
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.
这篇关于在 C# DllImport 中使用 32 位或 64 位 dll的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!