gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:11:51 26 4
gpt4 key购买 nike

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

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

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

DllImport[DLLImportString]

最佳答案

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

您可以使用 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();
}

或者你可以试试用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)

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();

关于c# - 我们如何动态更改 DLLImport 属性中的程序集路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5310014/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com