Search code examples
c#ipcshared-memory

Shared memory with pointer in C#


MemoryMappedFile seems to be the only way to share memory between processes in .NET(?), however I didn't find a way to map a region to the process' virtual memory space, so it can't be really treated as a memory block since there's no way to get the pointer. I'm using pointer to process bitmap for best performance and reusability.

In c++ this can be easily achieved using boost.

Is there a way share a region of memory between processes and use pointer to read/write data?


Solution

  • For lower level access you can use MemoryMappedViewAccessor.SafeMemoryMappedViewHandle which returns a SafeMemoryMappedViewHandle which has a load of lower level access methods.

    Here's an example:

    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();
            }
        }
    }