本文实例讲述了C++进程共享数据封装成类的方法,分享给大家供大家参考。具体方法如下:
ShareMemory.cpp源文件如下:
CShareMemory::CShareMemory(const char* pszMapName, int nFileSize, BOOL bServer):m_hFileMap(NULL),m_pBuffer(NULL)
{
if (bServer) //是服务端,就创建
{
m_hFileMap = ::CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_EXECUTE_READWRITE, 0, nFileSize, pszMapName);
}
else //否则就打开
{
m_hFileMap = ::OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, pszMapName);
}
//把它映射到内存
m_pBuffer = ::MapViewOfFile(m_hFileMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
}
CShareMemory::~CShareMemory(void)
{
::UnmapViewOfFile(m_pBuffer);
::CloseHandle(m_hFileMap);
}
ShareMemory.h头文件如下:
#include <Windows.h>
class CShareMemory
{
public:
CShareMemory(const char* pszMapName, int nFileSize=0, BOOL bServer=FALSE);
~CShareMemory(void);
//属性
LPVOID GetBuffer() const
{
return m_pBuffer;
}
//实现
private:
HANDLE m_hFileMap;
LPVOID m_pBuffer;
};
使用时用法如下:
服务端:
int main(int argc, char *argv[])
{
//进程间内存共享
LPCTSTR lpName= "hello";
LPCTSTR lpContent = "123456";
CShareMemory* pShareMemory = new CShareMemory(lpName, 20, FALSE);
LPVOID lpBase = pShareMemory->GetBuffer();
strcpy((char*)lpBase, lpContent);
printf("%s\n",(char*)pShareMemory->GetBuffer());
getchar();
return 0;
}
客户端:
int main(int argc, char *argv[])
{
//进程间内存共享
LPCTSTR lpName= "hello";
LPCTSTR lpContent = "123456";
CShareMemory* pShareMemory = new CShareMemory(lpName, 20, FALSE);
printf("%s\n",(char*)pShareMemory->GetBuffer());
getchar();
return 0;
}
希望本文所述对大家的C++程序设计有所帮助。