Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c#

How do we change the assembly path in DLLImport attribute inside an if conditional statement? e.g. I want to do something like this:

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

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

DllImport[DLLImportString]
like image 361
InfoLearner Avatar asked Dec 21 '22 16:12

InfoLearner


1 Answers

You can't set attribute's value wich is calculated during runtime

You can define two methods with diff DllImports and call them in your if statement

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

Or you can try to Load dll dynamicaly with winapi LoadLibrary

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

Create delegate that fits method in dll

delegate void CallMethod();

And then try to use something like that

   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();
like image 85
Stecya Avatar answered Dec 24 '22 06:12

Stecya