C++/CLI allows relatively easy wrapping of unmanaged elements into usable types from the managed world. In the unmanaged world, I’ve been using for years the notion of shared memory – the ability to share block of memory between OS processes in an easy way. I’ve not seen this exact functionality anywhere in the .NET framework, so I decided to implement a simple mechanism around the file mapping concept (as it’s referred in the SDK docs); and besides, it’s a nice enough thing to try with C++/CLI.
The native functions in question are CreateFileMapping, MapViewOfFile and friends. Quite easy to use natively, I’ve created a managed type called SharedMemory that encapsulates their use. An internal CriticalHandleZeroOrMinusOneIsInavlid-derived type encapsulates the resulting handle. Another internal type, SharedMemoryStream is responsible for abstracting the access to the memory block with a normal System.IO.Stream.
I’ve simplified the implementation by always creating a read/write block (the native API allows read only as well).
To actually share memory blocks, the same name (a simple string) must be supplied in the constructor. This will make sure the same kernel section object is accessed underneath.
The download includes two projects. The SharedLib project contains the C++/CLI implementation (all Visual Studio 2008). The second contains a simple Windows Forms test app. To try it, run 2 instances of the test app. In one instance, enter some text in the textbox and click Write. In the other instance, click Read. You should see the stored text. Of course, the data can be anything – anything you can put in a Stream.