2

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?

3
  • The documentation you linked shows you how to create the accessor: using (var accessor = mmf.CreateViewAccessor(offset, length)) - You can use accessor to read and write value type items (which includes POCO structs) to and from the MMF at any offset. Commented Oct 26, 2022 at 15:21
  • 2
    For lower level access you can use MemoryMappedViewAccessor.SafeMemoryMappedViewHandle which returns a SafeMemoryMappedViewHandle which has a load of lower level access methods. It even has AcquirePointer(Byte*) which returns a pointer to the start of the MMF view - but that requires unsafe code. Commented Oct 26, 2022 at 15:40
  • Thanks! The second one is exactly what I was looking for. I don't really mind using unsafe context. Would you like you post this as an answer? Commented Oct 27, 2022 at 0:56

1 Answer 1

3

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();
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.