c# - C# 中的指针共享内存

标签 c# ipc shared-memory

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/

相关文章:

c# - 在机器上没有安装 PFX 的情况下使用客户端证书发出 HTTP 请求?

c# - Xamarin iOS - 如何发送电子邮件

C# 同时重写和新建

linux - POSIX 共享内存和信号量权限由 open 调用错误设置

c - 使用共享内存时出现 "Bad system call"错误

c - 如何使用cuda对沿行方向的巨大二维矩阵进行归约? (每行的最大值和最大值的索引)

c++ - 如何有效地等待一组信号量?

c# - 您可以添加像静态方法一样调用的扩展方法吗?

c - 管道未发送准确信息

java - EhCache 是否像 MemCached 一样利用所有节点的内存?