首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

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

2012-05-22 
C#调用C++DLL时,出现尝试读取或写入受保护的内存。这通常指示其他内存已损坏。[DllImport(Iocp_dll.dll, E

C#调用C++DLL时,出现尝试读取或写入受保护的内存。这通常指示其他内存已损坏。
[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);
   
  }

[解决办法]
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);

[解决办法]
WinAPI的long类型是32位的,而C#的long是64位的,会引发PInvokeStackImbalance错误。因此需要将原来的long类型改为int类型,C#中int是32位的

热点排行