从C#方法,如何调用和运行DLL,其中DLL名称来自String变量?

时间:2012-10-10 15:16:11

标签: c# .net interop pinvoke

我是C#.NET的新手。我正在编写一个方法,我需要调用并运行DLL文件,其中DLL文件名来自String变量 -

String[] spl;

String DLLfile = spl[0];

如何导入此DLL并从DLL调用函数以获取返回值?我尝试了以下方式..

String DLLfile = "MyDLL.dll";

[DllImport(DLLfile, CallingConvention = CallingConvention.StdCall)]

但它没有用,因为字符串应该是'const string'类型而'const string'不支持变量。请帮我详细说明一下程序。感谢。

2 个答案:

答案 0 :(得分:5)

对于本机DLL,您可以创建以下静态类:

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

然后按如下方式使用它:

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

MyFunctionDelegatedelegate的位置。 E.g:

delegate void MyFunctionDelegate(int i);

答案 1 :(得分:3)

您可以使用LoadAssembly方法和CreateInstance方法来调用方法

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