C# 动态调用指定目录下C++ DLL记录

C# 动态调用C++ DLL记录

第一次使用动态调用C++DLL 参考了许多网上大佬的资料信息后,成功调用,特记录一下
可以指定路径的方法,这样可以调用外部的DLL。
正常LoadLibrary(“绝对路径”)是可以使用的,但是也不知道为什么自己的电脑不行,所以提前指定工作目录。
注意:每调用一次LoadLibrary都要调用一次FreeLibrary,以防内存泄漏

using System;
using System.Runtime.InteropServices;

namespace flashJob.SeedKeyDLL
{
    public static class InteropDemo
    {
            [DllImport("kernel32.dll", EntryPoint = "LoadLibrary")]
            public static extern int LoadLibrary(String funcname);//装载动态的库

            [DllImport("kernel32.dll", EntryPoint = "GetProcAddress")]
            public static extern int GetProcAddress(int handle, String funcname);

            [DllImport("kernel32.dll", EntryPoint = "FreeLibrary")]
            public static extern int FreeLibrary(int handle);
            ///<summary>
            /// 通过非托管函数名转换为对应的委托 
            ///</summary>
            ///<param name="dllModule"> 通过 LoadLibrary 获得的 DLL 句柄 </param>
            ///<param name="functionName"> 非托管函数名 </param>
            ///<param name="t"> 对应的委托类型 </param>
            ///<returns> 委托实例,可强制转换为适当的委托类型 </returns>
            public static Delegate GetFunctionAddress(int dllModule, string functionName, Type t)
            {
                int address = GetProcAddress(dllModule, functionName);
                if (address == 0)
                    return null;
                else
                    return Marshal.GetDelegateForFunctionPointer(new IntPtr(address), t);
            }
    }
  //实际应用
public static void GenerateKeyExFunctionGenerateKeyEx(params [])
        {
        //指定工作路径
        Directory.SetCurrentDirectory("DLL所在的目录,不包含文件名");
            //1.动态加载C++ Dll
             int hModule = InteropDemo.LoadLibrary("DLL的名字.dll");
           
            if (hModule == 0) return -1;
            //获得相应的委托实例
            GenerateKeyEx foo = (GenerateKeyEx)InteropDemo.GetFunctionAddress(hModule, "要调用的函数名", typeof(GenerateKeyEx));
            if (foo == null)
            {
                InteropDemo.FreeLibrary(hModule);
                return -1;
            }
            //调用函数
          foo(params []);
 InteropDemo.FreeLibrary(hModule);
        }

        /// <summary>
        /// 函数指针,一定要加上面这一行,最初没加,然后调试异常:
        /// </summary>
        /// <returns></returns>
        [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
        delegate int GenerateKeyEx(params []);


 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值