繁体   English   中英

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

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

我是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'不支持变量。 请帮我详细说明一下程序。 谢谢。

对于本机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 例如:

delegate void MyFunctionDelegate(int i);

您可以使用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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM