在c#里调用C++的dll时,需要注意的一些问题

在c#里调用C++的dll,遇到了一些头疼的问题:

C++里头文件定义形势如下:

typedef void (*CALLBACKFUN1W)(wchar_t*, void* pArg);
typedef void (*CALLBACKFUN1A)(char*, void* pArg);

bool BIOPRINT_SENSOR_API dllFun1(CALLBACKFUN1 pCallbackFun1, void* pArg);

在其中一个导入的dll方法里,有一个回调函数的参数

[DllImport("test.dll", EntryPoint = "dllFunc1", CharSet = CharSet.Unicode)]
  public static extern bool dllFunc1([MarshalAs(UnmanagedType.FunctionPtr)] CallbackFunc1 pCallbackFunc1 , IntPtr pArg);

回调函数在C#里定义成委托如下:
public delegate void CallbackFunc1(StringBuilder strName, IntPtr pArg);

 

调试运行,报错。
有时是直接出错退出,信息如下:
Buffer overrun detected!

Program:
...

A buffer overrun has been detected which has corrupted the program's internal state. The program cannot safely continue execution and must now be terminated.

有时则能运行起来,但会抛出异常:
System.AccessViolationException: 尝试读取或写入受保护的内存。这通常指示其他内存已损坏。

几经周折,觅得答案,原来是要指定 调用方式,如下就OK了:
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
  public delegate void CallbackFunc1(IntPtr hWnd, IntPtr pArg);

而系统默认方式为 CallingConvention.StdCall。


程序终于不报错了,但是又出现结果不对了

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值