Listing 1: The MapFile template
#include <string>
#include <windows.h>
template<typename T>
class MapFile
{
public:
// ctor to create the initial file mapping
explicit MapFile(const std::string &mapName,
DWORD maxSizeLow = 1000,
DWORD maxSizeHigh = 0) :
pMapFile(0),
pObj(0),
handle(0)
{
// create new file mapping
handle =
::CreateFileMapping(reinterpret_cast<HANDLE>(0xffffffff),
NULL,
PAGE_READWRITE,
maxSizeHigh,
maxSizeLow,
mapName.c_str());
if (handle == NULL)
{
throw int(::GetLastError()); // your error code here
}
pMapFile = static_cast<T *>(::MapViewOfFile(handle,
FILE_MAP_ALL_ACCESS,
0, // high offset
0, // low offset
0)); // num bytes to
// map
if (pMapFile == NULL)
{
throw int(::GetLastError());
}
// call placement new to create an object of type T, place it
// in the location pointed to by pMapFile and call the ctor
pObj = new (pMapFile) T;
}
// ctor to open an existing file mapping
MapFile(const std::string &mapName, bool inherit) :
pMapFile(0),
pObj(0),
handle(0)
{
// open existing file mapping
handle = ::OpenFileMapping(FILE_MAP_ALL_ACCESS,
inherit,
mapName.c_str());
if (handle == NULL)
{
throw int(::GetLastError());
}
pMapFile = static_cast<T *>(::MapViewOfFile(handle,
FILE_MAP_ALL_ACCESS,
0, // high offset
0, // low offset
0)); // num bytes to
// map
if (pMapFile == NULL)
{
throw int(::GetLastError());
}
//since this is an existing object, just point to it...no need to
//call ctor again
pObj = pMapFile;
}
~MapFile()
{
::UnmapViewOfFile(pMapFile);
pMapFile = 0;
pObj->~T();
pObj = 0;
::CloseHandle(handle);
}
T *get() { return pObj; }
// friend class T;
private:
// do not allow
MapFile();
MapFile(const MapFile &rhs);
MapFile &operator=(const MapFile &rhs);
T *pMapFile; // the data, I own
T *pObj; // the object to call methods on...I own and call
HANDLE handle;
};