C/C++ Tip #15: A Class for Handling Shared MemoryUnder Win32

Sarir Khamsi

This tip addresses the problem of using shared memory under Win32 and using the address returned from the system calls to instantiate an object in that memory. As you might guess, this technique uses placement new to construct the object in the address returned by the OS, but it also uses templates to allow any object to be constructed in that space.

The main idea is to encapsulate the memory management into one class: the MapFile template (see Listing 1). This encapsulation reduces the creation and access to shared memory to the following syntax:

// MyClass.hpp
class MyClass
{
public:
   // ...
   void f();
};

// code in process A
MapFile<MyClass> myMapfile("SomeName");
// get access to your class
MyClass *pMyClass = myMapfile.get();
pMyClass->f(); // call some member function

// code in process B
MapFile<MyClass> myMapfile("SomeName", true);
// get access to your class
MyClass *pMyClass = myMapfile.get();
pMyClass->f(); // call some member function
 
The constructor of MapFile above takes a string uniquely identifying the shared memory. Shared memory isn't shared unless there's someone else in the picture. As a result, two constructors are provided: one to create the shared memory and install your class at that location and one to use existing shared memory and just install your class at the same location. The creating constructor takes parameters similar to the Win32 CreateFileMapping, while the other contstructor is simplified to call MapViewOfFile. In order for two processes to use the same shared memory, they mus use the same string in the same constructor. The MapFile class takes care of doing the proper cleanup, including calling the destructor of your class.

About the Author

Sarir Khamsi has been working with software stuff since 1983 and C++ stuff since 1994. His main interests include C++, OOP, auto-code generation with Perl, and really loud music. He can be reached at sponge@futureone.com.