C++過程同享數據封裝成類實例。本站提示廣大學習愛好者:(C++過程同享數據封裝成類實例)文章只能為提供參考,不一定能成為您想要的結果。以下是C++過程同享數據封裝成類實例正文
本文實例講述了C++過程同享數據封裝成類的辦法,分享給年夜家供年夜家參考。詳細辦法以下:
ShareMemory.cpp源文件以下:
#include "ShareMemory.h"
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頭文件以下:
#pragma once
#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;
};
應用時用法以下:
辦事端:
#include "ShareMemory.h"
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;
}
客戶端:
#include "ShareMemory.h"
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++法式設計有所贊助。