C#调用C++的DLL函数另一则(delegate) z

使用DLLImport进行导入函数的事. C#调用C++的函数其实不止这一种方法, 还有一种方法是用delegate申明函数委托进行调用,这种方法略显麻烦,但是可以进行回调并应用指针.

在C#中,首先先要定义一个类,用来把DLL中函数地址转换成委托:

    public class DLLWrapper
    {
    ///<summary>
    /// API LoadLibrary
    ///</summary>
    [DllImport("Kernel32")]
    public static extern int LoadLibrary(String funcname);
     
    ///<summary>
    /// API GetProcAddress
    ///</summary>
    [DllImport("Kernel32")]
    public static extern int GetProcAddress(int handle, String funcname);
     
    ///<summary>
    /// API FreeLibrary
    ///</summary>
    [DllImport("Kernel32")]
    public static extern int FreeLibrary(int handle);
     
    ///<summary>
    ///通过非托管函数名转换为对应的委托, by jingzhongrong
    ///</summary>
    ///<param name="dllModule">Get DLL handle by LoadLibrary</param>
    ///<param name="functionName">Unmanaged function name</param>
    ///<param name="t">ManageR type对应的委托类型</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);
    }
     
    ///<summary>
    ///将表示函数地址的IntPtr实例转换成对应的委托, by jingzhongrong
    ///</summary>
    public static Delegate GetDelegateFromIntPtr(IntPtr address, Type t)
    {
    if (address == IntPtr.Zero)
    return null;
    else
    return Marshal.GetDelegateForFunctionPointer(address, t);
    }
     
    ///<summary>
    ///将表示函数地址的int转换成对应的委托,by jingzhongrong
    ///</summary>
    public static Delegate GetDelegateFromIntPtr(int address, Type t)
    {
    if (address == 0)
    return null;
    else
    return Marshal.GetDelegateForFunctionPointer(new IntPtr(address), t);
    }
    }

然后, 用delegate声明函数:

    delegate void _amDBRSetThermoModel(int mid, ref int errid);

再然后, 自己写个private的函数封装DLL中的函数, hModule()函数的作用是取得DLL的地址,用在多个输出函数中

    private int hModule()
    {
    int _hModule = DLLWrapper.LoadLibrary(DLLPATH);
    if (_hModule == 0)
    {
    return 0;
    }
    return _hModule;
    }
     
    private void amDBRInitialize()
    {
    try
    {
    _amDBRInitialize amf = (_amDBRInitialize)DLLWrapper.GetFunctionAddress(hModule(), "amDBRInitialize", typeof(_amDBRInitialize));
    amf();
    }
    catch (Exception e)
    {
    throw e;
    }
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值