共享内存的使用

来源:互联网 发布:linux arp 老化时间 编辑:程序博客网 时间:2024/04/29 16:06

BOOL CShareMemoryImage::InitMap()
{
 EnterCriticalSection(&m_cs);
 char szBuf[256] = { 0 };

 // 获取最小分页大小
 SYSTEM_INFO sysinfo;
 GetSystemInfo(&sysinfo);
 DWORD dwAllocationGranularity = sysinfo.dwAllocationGranularity;

 INT64 dwMemoryFileSize = 1024*1024;  //指定内存映射文件大小

 // 必须要为dwAllocationGranularity(64K)的整数倍
 int left = dwMemoryFileSize % dwAllocationGranularity;
 if (left != 0)
 {
  dwMemoryFileSize += (dwAllocationGranularity - left);
 }

 DWORD dwError = 0;
 
 // 文件方式创建共享内存
 HANDLE hFile = CreateFileA(fileName.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
 if (hFile == INVALID_HANDLE_VALUE)
 {
  dwError = GetLastError();
  sprintf_s(szBuf, "[CShareMemoryImage]CreateFile failed,GetLastError = %d\n", dwError);
  DebugStringA(szBuf);
  LeaveCriticalSection(&m_cs);
  return FALSE;
 }
 DebugStringA("[CShareMemoryImage]CreateFile success!\n");

 DWORD high = (dwMemoryFileSize >> 32) & 0xFFFFFFFF;// 高32位
 DWORD low = dwMemoryFileSize & 0xFFFFFFFF;// 低32位
 HANDLE hFileMapping = CreateFileMappingA(
  hFile,       // system paging file INVALID_HANDLE_VALUE
  NULL,                           // security attributes
  PAGE_READWRITE,                 // protection
  high,                           // high-order DWORD of size
  low,       // low-order DWORD of size
  fileName.c_str());               // name

 if (hFileMapping == NULL)
 {
  dwError = GetLastError();
  sprintf_s(szBuf, "[CShareMemoryImage]CreateFileMapping failed,GetLastError = %d\n", dwError);
  DebugStringA(szBuf);
  CloseHandle(hFile);
  LeaveCriticalSection(&m_cs);
  return FALSE;
 }
 else
 {
  DebugStringA("[CShareMemoryImage]CreateFileMapping success!\n");

  LPVOID pViewOfFile = MapViewOfFile(  // 映射
   hFileMapping,             // handle to file-mapping object
   FILE_MAP_ALL_ACCESS,        // desired access
   0,
   0,
   0);                         // map all file

  if (pViewOfFile == NULL)
  {
   dwError = GetLastError();
   sprintf_s(szBuf, "[CShareMemoryImage]MapViewOfFile failed,GetLastError = %d\n", dwError);
   DebugStringA(szBuf);
   CloseHandle(hFile);
   CloseHandle(hFileMapping);
   LeaveCriticalSection(&m_cs);
   return FALSE;
  }
  else
  {
   sprintf_s(szBuf, "[CShareMemoryImage]MapViewOfFile success,fileName = %s\n", fileName.c_str());
   DebugStringA(szBuf);
  }
 }
 LeaveCriticalSection(&m_cs);

 return TRUE;
}

0 0
原创粉丝点击