我们如何动态更改DLLImport属性中的程序集路径?

4

如何在if条件语句内更改DLLImport属性中的程序集路径? 例如,我想要做这样的事情:

string serverName = GetServerName();
if (serverName == "LIVE")
{
   DLLImportString = "ABC.dll";

}
else
{
DLLImportString = "EFG.dll";
}

DllImport[DLLImportString]
3个回答

6

您不能设置在运行时计算的属性值。

您可以使用不同的DllImports定义两个方法,并在if语句中调用它们。

DllImport["ABC.dll"]
public static extern void CallABCMethod();

DllImport["EFG.dll"]
public static extern void CallEFGMethod();

string serverName = GetServerName(); 
if (serverName == "LIVE") 
{ 
   CallABCMethod();
} 
else 
{ 
   CallEFGMethod();
}

或者您可以尝试使用winapi的LoadLibrary动态加载dll。

[DllImport("kernel32.dll", EntryPoint = "LoadLibrary")]
static extern int LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string lpLibFileName);

[DllImport("kernel32.dll", EntryPoint = "GetProcAddress")]
static extern IntPtr GetProcAddress( int hModule,[MarshalAs(UnmanagedType.LPStr)] string lpProcName);

[DllImport("kernel32.dll", EntryPoint = "FreeLibrary")]
static extern bool FreeLibrary(int hModule);

创建适合dll中方法的委托

delegate void CallMethod();

然后尝试使用类似这样的东西。
   int hModule = LoadLibrary(path_to_your_dll);  // you can build it dynamically
   if (hModule == 0) return;
   IntPtr intPtr = GetProcAddress(hModule, method_name);
   CallMethod action = (CallMethod)Marshal.GetDelegateForFunctionPointer(intPtr, typeof(CallMethod));
   action.Invoke();

路径将从数据库中检索,并且在项目的生命周期中会多次更改。我不想每次更改代码。 - InfoLearner

4
您需要通过LoadLibrary/GetProcAddress手动加载dll。
我曾有一个小应用程序也有同样的需求,并使用了c++/cli。
在c#中,它看起来应该像这样:
delegate int MyFunc(int arg1, [MarshalAs(UnmanagedType.LPStr)]String arg2);

public static void Main(String[] args)
{
    IntPtr mydll = LoadLibrary("mydll.dll");
    IntPtr procaddr = GetProcAddress(mydll, "Somfunction");
    MyFunc myfunc = Marshal.GetDelegateForFunctionPointer(procaddr, typeof(MyFunc));
    myfunc(1, "txt");
}

编辑:这里是完整的示例。


1

也许你可以使用条件编译来区分你的构建版本? 如果你能够/define一个构建版本是针对服务器A的,例如使用/define serverA进行编译,那么你就可以有

#if serverA
DllImport["ABC.dll"]
#else
DllImport["EFG.dll"]
#endif

更多#if信息


这就是我一直在寻找的解决方案!谢谢 :) - Didac Perez Parera

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接