在 C# 中以编程方式设置 dllimport [英] Setting dllimport programmatically in C#
问题描述
我在我的解决方案中使用了 DllImport
.
我的问题是我有同一个 DLL 的两个版本,一个是为 32 位构建的,另一个是为 64 位构建的.
I am using DllImport
in my solution.
My problem is that I have two versions of the same DLL one built for 32 bit and another for 64 bit.
它们都公开具有相同名称和相同签名的相同函数.我的问题是我必须使用两种静态方法来公开这些方法,然后在运行时使用 IntPtr
大小来确定要调用的正确方法.
They both expose the same functions with identical names and identical signatures.
My problem is that I have to use two static methods which expose these and then at run time use IntPtr
size to determine the correct one to invoke.
private static class Ccf_32
{
[DllImport(myDllName32)]
public static extern int func1();
}
private static class Ccf_64
{
[DllImport(myDllName64)]
public static extern int func1();
}
我必须这样做,因为 myDllName32
和 myDllName64
必须是常量,而且我还没有找到在运行时设置它的方法.
I have to do this because myDllName32
and myDllName64
must be constant and I have not found a way to set it at run time.
有没有人有一个优雅的解决方案,这样我就可以摆脱代码重复和常量 IntPtr
大小检查.
Does anyone have an elegant solution for this so I could get rid of the code duplication and the constant IntPtr
size checking.
如果我可以设置文件名,我只需要检查一次,我就可以摆脱大量重复的代码.
If I could set the file name, I would only have to check once and I could get rid of a ton of repeated code.
推荐答案
您或许可以使用 #if
关键字来实现这一点.如果你定义了一个名为 win32
的条件编译器符号,下面的代码将使用 win32 块,如果你删除它,它将使用另一个块:
You can probably achieve this with the #if
keyword. If you define a conditional compiler symbol called win32
, the following code will use the win32-block, if you remove it it will use the other block:
#if win32
private static class ccf_32
{
[DllImport(myDllName32)]
public static extern int func1();
}
#else
private static class ccf_64
{
[DllImport(myDllName64)]
public static extern int func1();
}
#endif
这可能意味着您可以删除您现在拥有的类包装:
This probably means that you can remove the class wrapping that you have now:
private static class ccf
{
#if win32
[DllImport(myDllName32)]
public static extern int func1();
#else
[DllImport(myDllName64)]
public static extern int func1();
#endif
}
为了方便起见,我想您可以创建构建配置来控制编译符号.
For convenience, I guess you could create build configurations for controlling the compilation symbol.
这篇关于在 C# 中以编程方式设置 dllimport的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!