关于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#的环境也是这个。

猜你喜欢

转载自blog.csdn.net/qq_25528267/article/details/87877773
今日推荐