首页 > 代码库 > 共享内存注意事项

共享内存注意事项

1.共享内存创建类

 

//构造函数,传递共享内存对象名称、大小

CFileMappingMgr::CFileMappingMgr(const CString & mapName, int mapSize)
{
m_nMapSize = mapSize;

m_hMapFile = CreateFileMapping(
INVALID_HANDLE_VALUE, // use paging file
NULL, // default security
PAGE_READWRITE, // read/write access
0, // maximum object size (high-order DWORD)
mapSize, // maximum object size (low-order DWORD)
mapName); // name of mapping object

if (m_hMapFile == NULL)
{
_tprintf(TEXT("Could not create file mapping object (%d).\n"),
GetLastError());
}
}

 

//获取共享内存所存储的变量

void * CFileMappingMgr::GetFileMapPtr()
{
void * pRet =
(void*) MapViewOfFile(m_hMapFile, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
m_nMapSize);

if (pRet == NULL)
{
_tprintf(TEXT("Could not map view of file (%d).\n"),
GetLastError());

CloseHandle(m_hMapFile);

return NULL;
}

return pRet;
}

 

2.使用

int mapSize = sizeof(CSDKMgr);
m_fileMgr = new CFileMappingMgr(L"Global\\MyFileMappingObject", mapSize);
m_pMapSdkMgr = (CSDKMgr*)m_fileMgr->GetFileMapPtr();
if (!m_pMapSdkMgr)
{
return FALSE;
}

int ret = CreateSingleSignal(L"Global\\CreateSingleSignal1");
if (ret == 0)//创建成功,表示尚未有人创建过
{
CSDKMgr* pSdkMgr = new CSDKMgr;

//给共享内存赋值
memcpy(m_pMapSdkMgr, pSdkMgr, mapSize);

//释放临时new生成的变量(并不会导致m_pMapSdkMgr对应的内存内容失效,函数地址已经存在了)
delete pSdkMgr;
pSdkMgr = NULL;
}

 

//创建命名的互斥变量

int CreateSingleSignal(const TCHAR *processUniqueName)
{
//-------防止多次起动----------
HANDLE hMutex = ::CreateMutex(0, true, processUniqueName);
int nRet = 0;
if (hMutex)
{
if(GetLastError() == ERROR_ALREADY_EXISTS)
{
nRet = 1;// 已存在进程,退出
}
else
{
nRet = 0; // 正常启动

}
}
else
{
nRet = -1;// 无法创建,退出
}

return nRet;
}

共享内存注意事项