MemoryMappedFile似乎是.NET(?)中进程之间共享内存的唯一方法,但是我没有找到将区域映射到进程虚拟内存空间的方法,因此它不能真正被视为内存块因为没有办法获取指针。 我使用指针来处理位图以获得最佳性能和可重用性。
In c++ this can be easily achieved using boost .
有没有办法在进程之间共享内存区域并使用指针来读取/写入数据?
最佳答案
对于较低级别的访问,您可以使用 MemoryMappedViewAccessor.SafeMemoryMappedViewHandle
它返回 SafeMemoryMappedViewHandle
它具有大量较低级别的访问方法。
这是一个例子:
static void Main()
{
// Open an MMF of 16MB (not backed by a system file; in memory only).
using var mmf = MemoryMappedFile.CreateOrOpen("mmfMapName", capacity: 16 * 1024 * 1024);
// Create an MMF view of 8MB starting at offset 4MB.
const int VIEW_BYTES = 8 * 1024 * 1024;
using var accessor = mmf.CreateViewAccessor(offset: 4 * 1024 * 1024, VIEW_BYTES);
// Get a pointer into the unmanaged memory of the view.
using var handle = accessor.SafeMemoryMappedViewHandle;
unsafe
{
byte* p = null;
try
{
// Actually get the pointer.
handle.AcquirePointer(ref p);
// As an example, fill the memory pointed to via a uint*
for (uint* q = (uint*)p; q < p + VIEW_BYTES; ++q)
{
*q = 0xffffffff;
}
}
finally
{
if (p != null)
handle.ReleasePointer();
}
}
}
关于c# - C# 中的指针共享内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74209536/