C# 动态加载dll

发布于:2024-04-14 ⋅ 阅读:(137) ⋅ 点赞:(0)

 方式1

using System;
using System.Reflection;
 
class Program
{
    static void Main()
    {
        string dllPath = "path/to/your/library.dll"; // 替换为你的DLL文件路径
        Assembly myAssembly = Assembly.LoadFile(dllPath);
        Type myType = myAssembly.GetType("YourNamespace.YourClass"); // 替换为你的类型名称
        object myInstance = Activator.CreateInstance(myType);
 
        // 调用DLL中的方法
        MethodInfo myMethod = myType.GetMethod("YourMethod"); // 替换为你的方法名称
        myMethod.Invoke(myInstance, null); // 如果方法不需要参数,使用null,否则提供适当的参数数组
 
        Console.WriteLine("DLL方法已被调用。");
    }
}

方式二 

 [DllImport("C:\\Program Files\\****\\****.dll")]
internal static extern int Function(int Code);

以上方式发现dll的路径是固定的,我们通过以下方式可以成功加载dll

var path = Environment.GetEnvironmentVariable("PATH");
if (path != null)
{
    path = path.TrimEnd(';')+";";
    var ProBinDir = "";//指定路径或者从注册表中获取
    if (ProBinDir != null)
        Environment.SetEnvironmentVariable("PATH", path += $"{ProBinDir}\\bin;");
    else
        Trace.TraceError("获取路径失败");
}
[DllImport("****.dll")]
internal static extern int Function(int Code);

实例

整体文件

步骤

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ZWH
{
    public class Class1
    {
        public void putoutZWH() 
        {
            Console.WriteLine("ZWH");
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp20
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 加载 ZWH.dll 程序集
            Assembly assembly = Assembly.LoadFrom("E:\\workspace\\ConsoleApp20\\ZWH\\bin\\Debug\\ZWH.dll");

            // 获取 ZWH.Class1 类型
            Type type = assembly.GetType("ZWH.Class1");

            // 创建 ZWH.Class1 的实例
            object obj = Activator.CreateInstance(type);

            // 获取 putoutZWH 方法的 MethodInfo
            MethodInfo method = type.GetMethod("putoutZWH");

            // 调用 putoutZWH 方法
            method.Invoke(obj, null);

            // 等待用户按下任意键退出程序
            Console.ReadKey();
        }
    }
}

 结果

参考文献

C#动态调用DLL_c# 动态加载dll-CSDN博客


网站公告

今日签到

点亮在社区的每一天
去签到