全局内存访问
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
.
- 使用
AllocCoTaskMem
方法不会改变任何东西。
- 像
4
一样为内存设置固定大小也无济于事。
- 两个App中的指针相同
- App B 中的读取缓冲区包含错误数据。 (不是 123,0,0,0)
有人知道我做错了什么吗?
正如评论中已经提到的,Marshaling 不能以这种方式使用。
应用程序不能自由读写彼此的内存。这是 O.S 的一大特色。使应用程序不会相互崩溃。
如果您想在 Windows 中的应用程序之间共享数据,您可以使用以下选项,as explained here:
- 剪贴板
- COM
- Data Copy
- Dynamic Data Exchange
- Memory mapped file
- Mailslots
- 管道
- Remote procedure Call
- Windows 套接字
在应用程序 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
.
- 使用
AllocCoTaskMem
方法不会改变任何东西。 - 像
4
一样为内存设置固定大小也无济于事。 - 两个App中的指针相同
- App B 中的读取缓冲区包含错误数据。 (不是 123,0,0,0)
有人知道我做错了什么吗?
正如评论中已经提到的,Marshaling 不能以这种方式使用。
应用程序不能自由读写彼此的内存。这是 O.S 的一大特色。使应用程序不会相互崩溃。
如果您想在 Windows 中的应用程序之间共享数据,您可以使用以下选项,as explained here:
- 剪贴板
- COM
- Data Copy
- Dynamic Data Exchange
- Memory mapped file
- Mailslots
- 管道
- Remote procedure Call
- Windows 套接字