I am new to C#.NET. I am writing a method where I need to call and run a DLL file, where the DLL file name comes from a String variable-
String[] spl;
String DLLfile = spl[0];
How do I import this DLL and call a function from the DLL to get the return value? I tried the the following way..
String DLLfile = "MyDLL.dll";
[DllImport(DLLfile, CallingConvention = CallingConvention.StdCall)]
But it did not worked, as The string should be in 'const string' type and 'const string' does not support variables. Please help me with detail procedure. Thanks.
For native DLLs you can create the following static class:
internal static class NativeWinAPI
{
[DllImport("kernel32.dll")]
internal static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll")]
internal static extern bool FreeLibrary(IntPtr hModule);
[DllImport("kernel32.dll")]
internal static extern IntPtr GetProcAddress(IntPtr hModule,
string procedureName);
}
And then use it as follows:
// DLLFileName is, say, "MyLibrary.dll"
IntPtr hLibrary = NativeWinAPI.LoadLibrary(DLLFileName);
if (hLibrary != IntPtr.Zero) // DLL is loaded successfully
{
// FunctionName is, say, "MyFunctionName"
IntPtr pointerToFunction = NativeWinAPI.GetProcAddress(hLibrary, FunctionName);
if (pointerToFunction != IntPtr.Zero)
{
MyFunctionDelegate function = (MyFunctionDelegate)Marshal.GetDelegateForFunctionPointer(
pointerToFunction, typeof(MyFunctionDelegate));
function(123);
}
NativeWinAPI.FreeLibrary(hLibrary);
}
Where MyFunctionDelegate
is a delegate
. E.g.:
delegate void MyFunctionDelegate(int i);
You can use LoadAssembly
method , and CreateInstance
method in order to invoke method
Assembly a = Assembly.Load("example");
// Get the type to use.
Type myType = a.GetType("Example");
// Get the method to call.
MethodInfo myMethod = myType.GetMethod("MethodA");
// Create an instance.
object obj = Activator.CreateInstance(myType);
// Execute the method.
myMethod.Invoke(obj, null);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With