AppDomain及LoadLibrary加载外部dll简单实例

namespace LoadLibrary
{
    class Program
    {

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, EntryPoint = "LoadLibrary")]
        static extern IntPtr LoadLibrary(string dllName);
        [DllImport("kernel32.dll")]
        static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, EntryPoint = "FreeLibrary")]
        static extern IntPtr FreeLibrary(IntPtr intPtr);

        delegate string AppMain(string a, string b);
        static void Main(string[] args)
        {
            //AppaDomin方式
            AppaDominLoadlibrary();
            //LoadLibrary方式
            AppLoadLibrary();
        }
        private static void AppLoadLibrary()
        {
            string path = $"{System.Environment.CurrentDirectory}\\AppDllExport.dll";
            if (File.Exists(path))
            {
                IntPtr intPtr = LoadLibrary(path);
                if (intPtr != null)
                {
                    IntPtr intPtr1 = GetProcAddress(intPtr, "AppMain");
                    AppMain appMain = (AppMain)Marshal.GetDelegateForFunctionPointer(intPtr1, typeof(AppMain));
                    string ret = appMain("你好", "LoadLibrary");
                    //对于使用dllexport的无法正常卸载
                    // FreeLibrary(intPtr);
                }
            }
        }
        private static void AppaDominLoadlibrary()
        {
            string path = $"{System.Environment.CurrentDirectory}\\AppDllExport.dll";
            if (File.Exists(path))
            {
                AppDomain appDomain = AppDomain.CreateDomain(path);
                Assembly assembly = appDomain.Load(new AssemblyName("AppDllExport"));
                object obj = assembly.CreateInstance("AppDllExport.AppRun");
                Type t = obj.GetType();
                string ret =  (string)t.InvokeMember("AppMain", BindingFlags.InvokeMethod, null, obj, new object[] { "你好", "AppDomain" });
                AppDomain.Unload(appDomain);
            }
        }
    }

    //本例子调用的dll内容参考
    //namespace AppDllExport
    //{
    //    public class AppRun
    //    {
    //        [DllExport(CallingConvention = CallingConvention.StdCall)]
    //        public static string AppMain(string a, string b)
    //        {
    //            return "return" + a + b;
    //        }
    //    }
    //}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值