Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/141.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在DLLImport属性中动态更改程序集路径?_C#_C++ - Fatal编程技术网

C# 如何在DLLImport属性中动态更改程序集路径?

C# 如何在DLLImport属性中动态更改程序集路径?,c#,c++,C#,C++,如何在if条件语句中更改DLLImport属性中的程序集路径? e、 g.我想这样做: string serverName = GetServerName(); if (serverName == "LIVE") { DLLImportString = "ABC.dll"; } else { DLLImportString = "EFG.dll"; } DllImport[DLLImportString] 无法设置在运行时计算的属性值 您可以使用diffDllImports定义两个方

如何在if条件语句中更改DLLImport属性中的程序集路径? e、 g.我想这样做:

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 DynamicCaly

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

可能您可以使用条件编译来区分您的构建? 如果您可以确定构建是针对服务器a的,例如使用/define serverA编译,那么您可以

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

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

编辑:是完整的示例

从数据库中检索路径,并且在项目生命周期内会多次更改。我不想每次都更改代码这是我一直在寻找的解决方案!谢谢:)