Shared Memory (Section) wrapper using C++/CLI

May 5, 2008

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.

Enjoy!

 

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

2 comments

  1. MattJanuary 27, 2010 ב 16:54

    Thanks much for this. This made my life infinitely easier on a project for work, do you want any sort of citation for this code? Also, is there any way to use the SharedMemory library in a gcc eclipse project?

    Reply
  2. pavelyJanuary 27, 2010 ב 18:47

    No need for a citation. Actually, the code probably needs some more work…
    Anyway, in upcoming .NET 4 there is an official wrapper for shared memory in System.IO.MemoryMappedFiles.
    I don’t think it’s possible to use it directly in GCC as it’s C++/CLI, that is, a .NET assembly.

    Reply