Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 483
user1735274 Avatar asked Oct 10 '12 15:10

user1735274


2 Answers

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);
like image 130
Nikolay Khil Avatar answered Oct 06 '22 23:10

Nikolay Khil


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);
like image 37
Aghilas Yakoub Avatar answered Oct 07 '22 00:10

Aghilas Yakoub