Windowsでファイルマッピングによる共有メモリの実現


Windowsの下でファイルマッピングを利用して共有メモリを実現する方法は比較的簡単で、以下は実現コードで、詳細は注釈で説明する.
linuxの下でshmのような操作を呼び出します.このクラスはあまりテストを行っていません.質問とbug~:)
#include 
#include 
#include 
#include 
using std::string;
using std::cout;
using std::endl;
#pragma warning(disable: 4311)

class shareMemory
{
private:
 LPWSTR shm_name_u;
 bool  is_create_file;
 void * sh_base;
 HANDLE semaphore;
 HANDLE file_mapping;
 int  addr_len;
public:

/*create_file                   ,         ,           release          ,             ,        shm_name  .        ,             */
 shareMemory(const string& shm_name, bool create_file=false):is_create_file(create_file)
 {   
  const char * _c_shm_name = shm_name.c_str();
  int _size =(int)shm_name.length()+1;
  shm_name_u=(LPWSTR)malloc(_size*2);
  MultiByteToWideChar(CP_ACP,0,_c_shm_name,_size,shm_name_u,_size);
  semaphore =  CreateSemaphore(NULL,1,1,NULL);
  sh_base = NULL;
  file_mapping = INVALID_HANDLE_VALUE;
 }

 void * shm_open(void* addr,const int length, DWORD protect)
 {   addr_len = length; 
 HANDLE _file_handle = INVALID_HANDLE_VALUE;
  if(is_create_file)
  {
  _file_handle=
   CreateFile(shm_name_u,GENERIC_READ|GENERIC_WRITE,0,
   NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);
#ifdef _DEBUG
  if(_file_handle==INVALID_HANDLE_VALUE)
   cout<size)
   _write_count = size;
/*  semaphore         (                  )*/
  WaitForSingleObject(semaphore,INFINITE);
  memcpy(dest,src,_write_count); 
  ReleaseSemaphore(semaphore,1,NULL);
  FlushViewOfFile(sh_base,_write_count);
  return _write_count;
 }

 /*         ,           **/
int  shm_read(void* src, void * dest, int size)
 {
  if(!check_adress(src))
   return -1;
    int _read_count = (int)sh_base+addr_len -(int) src;
 if(_read_count>size)
  _read_count = size;
 memcpy(dest,src,_read_count);
 return _read_count;
 }

 ~shareMemory()
 { 
   UnmapViewOfFile(sh_base);
   free(shm_name_u);
   CloseHandle(semaphore);
   CloseHandle(file_mapping);
 }

private :
/*      */
 bool check_adress(void* addr)
 {
 if( ( (int)addr  (int)sh_base+addr_len) )
  {
   SetLastError(ERROR_ACCESS_DENIED);
#ifdef _DEBUG
   printf("access denied,the destination address out of the map view!");
#endif //_DEBUG
   return  false;
  }
 return true;
 }
};

テスト:書き込みプロセスのメイン関数:
int main()
{
 shareMemory sm("boost", false);
 void * bs = sm.shm_open(NULL,1000*4,FILE_MAP_WRITE);
 if(bs==NULL)
  return -1;
 int a[10];
 for(int i=0; i<10; ++i)
  a[i] = i;
 sm.shm_write(bs,a,10*4);
 Sleep(100000);
}

リードプロセスの主関数:
int main()
{
 shareMemory sm("boost", false);
 void * bs = sm.shm_open(NULL,1000,FILE_MAP_READ);
 if(bs==NULL)
 {   cout<

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
http://blog.csdn.net/zhao_fu_lu/article/details/41730699