【转】VC++6.0共享内存

VC++6.0共享内存技术总结

程序1 -- 建立共享区,写数据:

int main(int argc, char* argv[])
{
 HANDLE lhShareMemory;
 char* lpBuffer = NULL;
 
 lhShareMemory = CreateFileMapping(HANDLE(0xFFFFFFFF), NULL, PAGE_READWRITE,
  0, 10, "mySharedMemory");
 
 if (NULL == lhShareMemory)
 {
  if (ERROR_ALREADY_EXISTS == GetLastError())
  {
   cout << "Already exists!";
  }
  else
  {
   cout << "Create Sheared Memory unsuccessfully!";
  }
  return 0;
 }
 
 lpBuffer = (char*)MapViewOfFile(lhShareMemory, FILE_MAP_WRITE, 0, 0, 10);
 if (NULL == lpBuffer)
 {
  cout << "Get Share memory unsuccessfully!";
  return 0;
 }
 
 strcpy(lpBuffer, "hello");
 cout << "进程通信:采用共享内存" << endl;
 cout << "写进程" << endl;
 cout << "写入数据:"<< endl<<lpBuffer << endl;
 Sleep(100000);
 UnmapViewOfFile(lpBuffer);
 return 0;
}

  

程序2 -- 使用共享区,读数据:

int main(int argc, char* argv[])
{
 HANDLE lhShareMemory;
 char* lpcBuffer;
 
 lhShareMemory = OpenFileMapping(FILE_MAP_READ, false, "mySharedMemory");
 if (NULL == lhShareMemory)
 {
  cout << "Open share memory unsuccessfully!" << endl;
  DWORD ldwError = GetLastError();
  cout << ldwError;
  return 0;
 }
 
 lpcBuffer = (char*)MapViewOfFile(lhShareMemory, FILE_MAP_READ, 0, 0, 100);
 if (NULL == lpcBuffer)
 {
  cout << "Open share memory unsuccessfully!";
  return 0;
 }
 cout << "进程通信:采用共享内存" << endl;
 cout << "读进程" << endl;
 cout << "读入数据:" << endl;
 for (int i = 0; i < 100; ++i)
 {
  cout << *(lpcBuffer + i);
 }
 UnmapViewOfFile(lpcBuffer);
 return 0;
}

 

详情请参考附件里完整的工程。

 

你可能感兴趣的:(vc++)