日期:2014-05-18  浏览次数:21071 次

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位的