C#调用C++DLL时,出现尝试读取或写入受保护的内存。这通常指示其他内存已损坏。

tiyo168 2012-05-19 11:29:36
[DllImport("Iocp_dll.dll", EntryPoint = "_SendPacket@16", CharSet = CharSet.Auto)]
public static extern int SendPacket(ulong time, int index,ref byte[] buf, int length);

private unsafe void btnStart_Click(object sender, EventArgs e)
{
byte[] sun = new byte[9];
string dig = "dig";
byte[] encodedBytes = Encoding.ASCII.GetBytes(dig);


sun[0] = (byte)(len / 256);
sun[1] = (byte)(len % 256);
sun[2] = message[0];
sun[3] = message[1];
for (i = 0; i < encodedBytes.Length; i++)
{
sun[4 + i] = encodedBytes[i];
}
byte[] crc_data = new byte[5];
crc_data[0] = message[0];
crc_data[1] = message[1];

for (int j = 0; j < 3; j++)
{
crc_data[j + 2] = encodedBytes[j];
}
ushort crcm = (ushort)CRC.MakeCRC(crc_data, 5);

sun[7] = (byte)(crcm % 256);
sun[8] = (byte)(crcm / 256);
Iocp.SendPacket(tt, index,ref sun, 9);

}
...全文
215 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
love_4023 2012-05-21
  • 打赏
  • 举报
回复
应该是函数的类型转换的问题。我之前调用C++的dll的时候也出现过这样的问题。
mizuho_2006 2012-05-21
  • 打赏
  • 举报
回复
WinAPI的long类型是32位的,而C#的long是64位的,会引发PInvokeStackImbalance错误。因此需要将原来的long类型改为int类型,C#中int是32位的
只在此山中 2012-05-21
  • 打赏
  • 举报
回复
ulong 改 uint :
[DllImport("Iocp_dll.dll", EntryPoint = "_SendPacket@16", CharSet = CharSet.Auto)]
public static extern int SendPacket(uint time, int index,ref byte[] buf, int length);
loveSoftandhxy 2012-05-21
  • 打赏
  • 举报
回复
我在使用过程中,经常遇到此问题
1,检查C++到C#之间的类型转换
2.根据C++的引用,或者指针,传入的时候,ref,out,或者空都会导致此问题
tiyo168 2012-05-21
  • 打赏
  • 举报
回复
C++的原函数:
extern "C" IOCPSERVERDLL_API int _stdcall SendPacket(unsigned long time, int index, char *buf, int length);
cnfixit 2012-05-19
  • 打赏
  • 举报
回复
把SendPacket的函数原形贴出来会好些

111,126

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧