#include <string>
using namespace
std;
/**************************************************************************************************
CMemMapFile
A Class to store a structure in a memory mapped file.
The purpose for using a memory mapped file is to cross process boundaries.
This simple class only has a constructor, destructor, and accessor.
Use is as follows:
struct MyDataStruct // this could also be “class MyDataStruct“
{
int x;
int y;
}
SomeFunctionThatNeedsMemoryMappedData()
{
// create the data file
CMemMapFile<MyDataStruct> myData(_T(“MyFunctionsMemoryMappedDataFile“));
// use the data file
if(myData)
{
myData->x = 5; // assign, which stores to mem mapped file
myData->y = 5;
cout << myData->x; // access data (from mem mapped file)
cout << myData->y;
}
else
cout << “Construction of myData failed!!”
// destructor will get called when myData goes out of scope, and get rid of file
}
**************************************************************************************************/
template <class T>
class CMemMapFile
{
public:
CMemMapFile(wstring Name); // must construct with a name
~CMemMapFile(); // destructor
T* operator–>() { return m_pData; } // access data with pointer operator e.g. myData->x = 5;
operator bool() { return m_hFile && m_pData; } // test for validity e.g if(myData)…
private:
HANDLE m_hFile;
T* m_pData;
};
template <class T>
CMemMapFile<T>::CMemMapFile(wstring Name)
{
m_hFile = NULL;
m_pData = NULL;
if(Name.length() == 0) return;
m_hFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(T), Name.c_str());
if (m_hFile)
{
m_pData = (T*) MapViewOfFile(m_hFile, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
if (!m_pData)
CloseHandle(m_hFile);
}
}
template <class T>
CMemMapFile<T>::~CMemMapFile()
{
if(m_pData)
UnmapViewOfFile(m_pData);
if(m_hFile)
CloseHandle(m_hFile);
}