from a C# method, how to call and run a DLL, where the DLL name comes from a String variable?

.net, c#, interop, pinvoke

Solution

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

Problem

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.

Original source