全局内存访问

时间:2017-01-09 16:50:44

标签: c# marshalling unmarshalling

在App A中,整数被写入ram。

var intBytes = BitConverter.GetBytes(123);
var allocatedMemory = Marshal.AllocHGlobal(intBytes.Length);
Marshal.Copy(intBytes, 0, allocatedMemory, intBytes.Length);

然后将指针发送到App B,再次读取整数。

 byte[] buffer = new byte[Marshal.SizeOf<int>()];
 Marshal.Copy(allocatedMemory, buffer, 0, buffer.Length);
 var myRecievedInteger = BitConverter.ToInt32(buffer, 0);

问题是App B的随机值是错误的,有时App B中的Marshal.Copy方法会抛出System.AccessViolationException

  • 使用AllocCoTaskMem方法不会改变任何内容。
  • 4这样的内存设置固定大小也无济于事。
  • 两个应用程序中的指针都相同。
  • App B中的读取缓冲区包含错误数据。 (不是123,0,0,0)

有人知道我做错了吗?

1 个答案:

答案 0 :(得分:3)

正如评论中已经提到的那样,Marshaling不能以这种方式使用。

应用程序不能自由地写入和读取彼此的内存。这是O.S.的一大特色。这使得应用程序不会互相崩溃。

如果要在Windows中的应用程序之间共享数据,可以使用以下选项as explained here

相关问题