簡體   English   中英

我們如何在DLLImport屬性中動態更改程序集路徑?

[英]How do we dynamically change the assembly path in DLLImport attribute?

我們如何在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 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);

創建適合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();

您需要通過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");
}

編輯: 是完整的例子

您可以使用條件編譯來區分構建嗎? 如果你可以/定義構建是針對服務器A的,例如。 使用/ define serverA編譯,然后就可以了

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

更多#if信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM