首页 新闻 会员 周边

C#调用C++动态库报尝试读写受保护内存的错

0
悬赏园豆:50 [已解决问题] 解决于 2015-04-27 15:22

一般来说,参数类型错误会导致这种错,我的参数应该没问题的,直接贴代码吧

C++接口声明

XXX_API BOOL writeBufNodeData(XXX_FILE *pFile, long long filePos, int len, unsigned char *pBuf);

C#声明

[DllImport("XXX.dll", EntryPoint = "writeBufNodeData", CallingConvention = CallingConvention.Cdecl)]
public static extern bool WriteBufNodeData(ref XXXStruct file, long filePos, int len, IntPtr bufferPtr);
[DllImport(
"XXX.dll", EntryPoint = "writeBufNodeData", CallingConvention = CallingConvention.Cdecl)] public static extern bool WriteBufNodeData(ref XXXStruct file, long filePos, int len, [In, Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)]byte[] buffer);

C#试了2种方式,第一种申请一块非托管内存传递,第二种是托管数组加上修饰,调用的时候均会出错

奇怪的是,我把C#程序生成了给C++开发进行调试没有问题,内存中的数据也是对的(我对比了传递之前和C++收到的数据),我这一调用就会出错,求大神解答

问题补充:

神奇的是,我在其他同事电脑上试也是正常的,就我这边出错,直接运行程C++ Dll序崩溃会有dmp文件,C++拿去看说是他拿到数据后找不到地方写导致崩溃。。。是我的电脑有问题吗

ever_Young的主页 ever_Young | 初学一级 | 园豆:159
提问于:2015-04-27 13:22
< >
分享
最佳答案
0

int writeBufNodeData(IntPtr pFile, int64 filePos, int len, IntPtr pBuf);

然后原来的 C++ API 有问题,pBuf 没有指定大小。

收获园豆:50
Launcher | 高人七级 |园豆:45045 | 2015-04-27 13:30

这个大小是由C#定的,然后C++读取 len 长度的数据

ever_Young | 园豆:159 (初学一级) | 2015-04-27 14:11

@ever_Young: 你是说 len 表示的是 pBuf 的长度吗?

Launcher | 园豆:45045 (高人七级) | 2015-04-27 14:32

@Launcher: 算是吧,C#传给C++,表示C#写了多少字节,然后C++也就读取相应数量的数据

ever_Young | 园豆:159 (初学一级) | 2015-04-27 14:38

@ever_Young: 算了,你这 API 定义的问题大了,你直接把 C++ 的实现代码贴出来吧。

Launcher | 园豆:45045 (高人七级) | 2015-04-27 14:45

@Launcher: 找到原因了,C++代码问题。。。也谢谢大神了:-)

ever_Young | 园豆:159 (初学一级) | 2015-04-27 15:21
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册