共享内存的包装类
使用内存映射文件在进程之间共享信息。
引言
在 Windows 平台上,进程间如何共享信息? 可以这样想:两个进程都打开同一个文件,并且都从中读取和写入,从而共享信息。 问题是,执行所有这些 fseek()
操作以及其他操作有时会很麻烦。 如果你可以将文件的某个部分映射到内存,并获取指向它的指针,那不是更容易吗? 然后你可以简单地使用指针运算来获取(和设置)文件中的数据。
这正是内存映射文件的作用。 而且它也真的很容易使用。 几个简单的调用,加上一些简单的规则,你就可以像个疯子一样进行映射了。
以下是来自 MSDN 文档的引用
“内存映射文件,或文件映射,是将文件的内容与进程的虚拟地址空间的一部分关联的结果。 它可用于在两个或多个进程之间共享文件或内存……”
微软提供了简单的 Windows API 函数来实现内存映射文件,例如 CreateFileMapping OpenFileMapping MapViewOfFile
,但我认为对于初学者来说使用起来并不容易。 因此,我实现了一个内存映射文件封装类。 希望它能帮助你。
它是如何工作的?
类 MMF
/**
* @author Bony.Chen
* @description A wrapped class managing file mapping object
for the specified file.It encapsulates some
basic operations such as Create,Open,MapViewOfFile.
* @mail bonyren@163.com
*/
class MMF
{
public:
MMF(const string& szMMName);
public:
virtual ~MMF(void);
public:
///Create memory mapping file
bool CreateMapFile();
///open memory mapping file that has been existing
bool OpenMapFile();
///close the handle of memory mapping file
void CloseMapFile();
///write data to the memory mapping file
bool WriteData(const char* szData,int nLen);
///read data from the memory mapping file
bool ReadData(string& szData);
private:
HANDLE m_hMapFile;//<the handle of memory-mapped file
string m_szMMName;//<the name of memory-mapped file
};
类 SharedMemory
class SharedMemory
{
/************************************************************************/
/*
the class SharedMemory uses the Singleton pattern
* @author Bony.Chen
* @description
the SharedMemory object can contain multiple memory-mapped
file objects and one MMF object has special name.the object
is implemented using Singleton pattern.
* @mail bonyren@163.com
*/
/************************************************************************/
protected:
SharedMemory();
private:
SharedMemory(const SharedMemory& sm)
{
}
SharedMemory& operator= (const SharedMemory& sm)
{
}
public:
virtual ~SharedMemory(void);
public:
///Get the only instance object
static SharedMemory& Instance();
///write data to the special MMF that named 'szName'
bool WriteSharedMemory(const string& szName,const string& szValue);
///read data from the special MMF that named 'szName'
bool ReadSharedMemory(const string& szName,string& szValue);
///delete the special MMF that named 'szName'
void DeleteSharedMemory(const string& szName);
private:
map<string,MMF*> m_mapMMF;//<the container of MMFs
};
如何使用?
进程1
int _tmain(int argc, _TCHAR* argv[])
{
SharedMemory& sm = SharedMemory::Instance();
string szValue("bonyren@gmail.com");
bool bRet = sm.WriteSharedMemory("1",szValue);
if(bRet)
{
printf("write value is %s",szValue.c_str());
}
sm.DeleteSharedMemory("1");
return 0;
}
进程2
int _tmain(int argc, _TCHAR* argv[])
{
SharedMemory& sm = SharedMemory::Instance();
string szValue;
bool bRet = sm.ReadSharedMemory("1",szValue);
if(bRet)
{
printf("read value is %s",szValue.c_str());
}
sm.DeleteSharedMemory("1");
return 0;
}
历史
- 2007年7月9日:初始发布