全局内存访问

Global memory access

在应用程序 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);

问题是应用程序 B 获取了错误的随机值,有时应用程序 B 中的 Marshal.Copy 方法抛出 System.AccessViolationException.

有人知道我做错了什么吗?

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

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

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