关于C#调用C++dll文件的异常处理 ——“尝试读取或写入受保护的内存。这通常指示其他内存已损坏。”

【原因1】
C++和C#的参数类型对应问题(详细内容参考链接:https://jljlpch.iteye.com/blog/520509)
【举例】
如C++:
bool __declspec(dllimport) getImage(unsigned char** ppImage, int& nWidth, int& nHeight);
对应C#成:
[DllImport(“test.dll”)]
public static extern bool getImage(ref IntPtr ppImage, ref int nWidth, ref int nHeight);
在C#调用时要定义:
IntPtr pImage = new IntPtr();
int refWidth = 0, refHeight = 0;
getImage(ref pImage, ref refWidth, ref refHeight);
【总结】
凡是双针指类型参数,可以用 ref IntPtr;而对于 int*, int&, 则都可用 ref int 对应
【C#与C++之间类型的对应】
(详细内容参考链接:http://www.cnblogs.com/zjoch/p/5999335.html)

【原因2】需指定调用方式,如下:
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void CallbackFunc1(IntPtr hWnd, IntPtr pArg);
而系统默认方式为 CallingConvention.StdCall。

【原因3】环境不一致
在用C++生成DLL的时候,和在C#中使用DLL时候,环境要相同,否则会报异常。我的是X64系统,和vs2012。所以生成DLL的环境也应该是这个,C#的环境也是这个。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值