C++进程共享数据封装成类实例
本文实例讲述了C++进程共享数据封装成类的方法,分享给大家供大家参考。具体方法如下:
ShareMemory.cpp源文件如下:
#include"ShareMemory.h" CShareMemory::CShareMemory(const char*pszMapName,intnFileSize,BOOLbServer):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头文件如下:
#pragmaonce #include<Windows.h> classCShareMemory { public: CShareMemory(const char*pszMapName,intnFileSize=0,BOOLbServer=FALSE); ~CShareMemory(void); //属性 LPVOIDGetBuffer()const { returnm_pBuffer; } //实现 private: HANDLEm_hFileMap; LPVOIDm_pBuffer; };
使用时用法如下:
服务端:
#include"ShareMemory.h" intmain(intargc,char*argv[]) { //进程间内存共享 LPCTSTRlpName="hello"; LPCTSTRlpContent="123456"; CShareMemory*pShareMemory=newCShareMemory(lpName,20,FALSE); LPVOIDlpBase=pShareMemory->GetBuffer(); strcpy((char*)lpBase,lpContent); printf("%s\n",(char*)pShareMemory->GetBuffer()); getchar(); return0; }
客户端:
#include"ShareMemory.h" intmain(intargc,char*argv[]) { //进程间内存共享 LPCTSTRlpName="hello"; LPCTSTRlpContent="123456"; CShareMemory*pShareMemory=newCShareMemory(lpName,20,FALSE); printf("%s\n",(char*)pShareMemory->GetBuffer()); getchar(); return0; }
希望本文所述对大家的C++程序设计有所帮助。