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

Inf*_*ner 4 c# c++

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

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

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

DllImport[DLLImportString]
Run Code Online (Sandbox Code Playgroud)

Ste*_*cya 6

您无法设置在运行时计算的属性值

您可以使用diff定义两个方法,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();
}
Run Code Online (Sandbox Code Playgroud)

或者您可以尝试使用winapi LoadLibrary加载dll dynamicaly

[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);
Run Code Online (Sandbox Code Playgroud)

创建适合dll方法的委托

delegate void CallMethod();
Run Code Online (Sandbox Code Playgroud)

然后尝试使用类似的东西

   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();
Run Code Online (Sandbox Code Playgroud)