1、首先创建一个互斥体对象。
#define SHARE_MUTEX _T("Your Mutex Name")
HANDLE hShareMuex = OpenMutex(MUTEX_ALL_ACCESS,FALSE,SHARE_MUTEX);
if(hShareMuex==NULL)
{
hShareMuex=CreateMutex(NULL, FALSE, SHARE_MUTEX);
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
};
}
2、创建共享内存
#define SHARE_MAPFILE _T("Your MapFile Name")
HANDLE hMapFile = CreateFileMapping(NULL, NULL, PAGE_READWRITE, 0, sizeof(ShareMemory), SHARE_MAPFILE);
if (hMapFile == NULL)
{
PrintOutput(_T("创建内存共享失败!! %s"), GetErrorMessage(GetLastError()));
return FALSE;
}
之后调用下面的函数进行读写该内存
3、读写共享内存的函数
struct ShareMemory
{
//......你的内存结构定义
}
//获取共享内存数据并锁定
static BOOL GetShareMemory_Lock(OUT HANDLE& hHandle,ShareMemory* psf=NULL)
{
HANDLE hMutex=OpenMutex(MUTEX_ALL_ACCESS,FALSE,SHARE_MUTEX);
if(hMutex==NULL)
{
return FALSE;
}
DWORD dwRet=WaitForSingleObject(hMutex,INFINITE);
if(dwRet!=WAIT_OBJECT_0)
{
CloseHandle(hMutex);
return FALSE;
}
hHandle=hMutex;
HANDLE hMap = OpenFileMapping(FILE_MAP_READ | FILE_MAP_WRITE, TRUE, SHARE_MAPFILE);
if(hMap==NULL)
{
return FALSE;
}
void* pFile = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ, 0, 0, 0);
if (pFile == NULL)
{
return FALSE;
}
if(psf!=NULL)
*psf = *(ShareMemory*)pFile;
UnmapViewOfFile(pFile);
CloseHandle(hMap);
// ReleaseMutex(hMutex);
// CloseHandle(hMutex);
return TRUE;
}
//写入共享内存数据并解锁
static BOOL SetShareMemory_UnLock(IN HANDLE hHandle,ShareMemory* psf=NULL)
{
HANDLE hMutex=hHandle;
HANDLE hMap = OpenFileMapping(FILE_MAP_READ | FILE_MAP_WRITE, TRUE, SHARE_MAPFILE);
if(hMap==NULL)
{
return FALSE;
}
void* pFile = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ, 0, 0, 0);
if (pFile == NULL)
{
return FALSE;
}
if(psf!=NULL)
*(ShareMemory*)pFile = *psf;
BOOL s=FlushViewOfFile(pFile,sizeof(ShareMemory));
// ShareMemory temp;
// temp=*(ShareMemory*)MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ, 0, 0, 0);
UnmapViewOfFile(pFile);
CloseHandle(hMap);
ReleaseMutex(hMutex);
CloseHandle(hMutex);
return TRUE;
}
static BOOL GetShareMemory(ShareMemory& sf)
{
HANDLE hMutex=OpenMutex(MUTEX_ALL_ACCESS,FALSE,SHARE_MUTEX);
if(hMutex==NULL)
{
return FALSE;
}
DWORD dwRet=WaitForSingleObject(hMutex,INFINITE);
if(dwRet!=WAIT_OBJECT_0)
{
CloseHandle(hMutex);
return FALSE;
}
HANDLE hMap = OpenFileMapping(FILE_MAP_READ | FILE_MAP_WRITE, TRUE, SHARE_MAPFILE);
if(hMap==NULL)
{
return FALSE;
}
void* pFile = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ, 0, 0, 0);
if (pFile == NULL)
{
return FALSE;
}
sf = *(ShareMemory*)pFile;
UnmapViewOfFile(pFile);
CloseHandle(hMap);
ReleaseMutex(hMutex);
CloseHandle(hMutex);
return TRUE;
}