5

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

String[] spl;

String DLLfile = spl[0];

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

String DLLfile = "MyDLL.dll";

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

但它不起作用,因为字符串应该是 'const string' 类型,而 'const string' 不支持变量。请帮我详细的程序。谢谢。

4

2 回答 2

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

MyFunctionDelegate一个在哪里delegate。例如:

delegate void MyFunctionDelegate(int i);
于 2012-10-10T15:34:52.167 回答
3

您可以使用LoadAssemblymethod 和CreateInstancemethod 来调用方法

        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);
于 2012-10-10T15:17:36.470 回答