Shared memory between 2 processes (applications)

Right now, .NET doesn’t support sections (aka Memory Mapped Files). It will soon, the 4.0 version has the System.IO.MemoryMappedFiles namespace. There is a good reason it took so long and also the reason you are not going to be happy with this addition. Using pointers is mandatory in MMFs, the shared memory is made available at a specific address. To share a value, you’ll have to write it to a specific address.

Pointers are however fundamentally incompatible with the managed memory model. Objects are created in a garbage collected heap, the collector moves them around as needed to keep the heap compacted. In a managed language, you have a reference to such an object, also knows as a “tracking handle”. The C/C++ equivalent is a pointer, but it is one with bells on, the garbage collector can always find it back and update its value. The CLR does support the notion of “pinning”, it converts a reference to a pointer. It implements this by marking the object as unmoveable. That however doesn’t help implement shared memory through an MMF, the object is pinned in the GC heap instead of the virtual memory address where the MMF view is located.

To make an MMF work, the object needs to be copied from the GC heap to the shared memory. That requires serialization. The .NET 4.0 class is named MemoryMappedViewStream. You probably can see where this is going, this is indistinguishable from using a named pipe or a socket. Getting data in and out of an MMF takes the same amount of effort. An MMF is merely slightly more efficient because the underlying buffer is not in the kernel memory pool.

You can break the rulez and do so today. You can P/Invoke the CreateFileMapping, OpenFileMapping and MapViewOfFile you need to create an MMF. And use the unsafe keyword so you can create pointers. You’ll need to use value types (like struct) for the shared memory elements or use the Marshal class.

Leave a Comment