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

use*_*274 5 .net c# pinvoke interop

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

String[] spl;

String DLLfile = spl[0];
Run Code Online (Sandbox Code Playgroud)

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

String DLLfile = "MyDLL.dll";

[DllImport(DLLfile, CallingConvention = CallingConvention.StdCall)]
Run Code Online (Sandbox Code Playgroud)

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

Nik*_*hil 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);
}
Run Code Online (Sandbox Code Playgroud)

然后使用如下:

// 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);
}
Run Code Online (Sandbox Code Playgroud)

哪里MyFunctionDelegatedelegate.例如:

delegate void MyFunctionDelegate(int i);
Run Code Online (Sandbox Code Playgroud)


Agh*_*oub 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);
Run Code Online (Sandbox Code Playgroud)

  • @DavidHeffernan,是的,我只是说我也犯过一次这个错误:-) OP 没有参与这次讨论,这太糟糕了,就好像他不太关心他的问题一样。 (2认同)