内存映射的作用之一是可以在进程之间进行通信,
鉴于自己当时搜索资料时的痛苦,以及有很多网友虽然知道有这几个函数,但是不知道怎么结合用,下面我列出了一个应用的例子:
SData是一个结构体,
创建内存映射
// mapping data
int iLengByte = sizeof(SData);
LPBYTE lpData;
HANDLE hMap = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE | SEC_COMMIT, 0,iLengByte, "S_DATA");
if (hMap != NULL)
{
lpData = (LPBYTE)MapViewOfFile(hMap, FILE_MAP_WRITE, 0, 0, 0);
if (lpData == NULL)
{
CloseHandle(hMap);
hMap = NULL;
return;
}
SData Data;
memcpy(lpData,(LPBYTE)(&Data),iLengByte);//copy head data to mapping file
}
//free the resource
if (hMap != NULL)
{
UnmapViewOfFile(lpData);
lpData = NULL;
CloseHandle(hMap);
hMap = NULL;
}
打开内存映射并使用
struct SData data;
HANDLE m_hMap = OpenFileMapping(FILE_MAP_READ, FALSE, "S_DATA");
if (m_hMap == NULL) return;
LPBYTE lpData = (LPBYTE)MapViewOfFile(m_hMap,FILE_MAP_READ,0,0,0);
if (lpData == NULL)
{
CloseHandle(m_hMap);
m_hMap=NULL;
return;
}
memcpy(&data, (SData*)(lpData), sizeof(SData));//copy the head data
//release mem
UnmapViewOfFile(lpData);
lpData = NULL;
CloseHandle(m_hMap);
m_hMap = NULL;