共用記憶體vc++技術

來源:互聯網
上載者:User
一、進程之間資料的共用:共用記憶體vc++技術

選自:http://www.xici.net/d49241289.htm

進程之間資料的共用可以用共用記憶體實現,在Win32中,進程之間共用記憶體使用量的事對應檔。虛擬記憶體系統具有把實際記憶體映射到頁檔案或者分頁檔的能力。使用者可以把記憶體映射到任何的對應檔中,包括系統記憶體頁。而利用系統記憶體頁可以實現快捷的記憶體共用。     利用共有記憶體實現進程之間的資料共用共有兩部:一.    使用CreateFileMapping函數建立記憶體對應檔。此函數需要檔案控制代碼,對於大多數的記憶體共用應用程式,建此檔案控制代碼設定為0xFFFFFFFF即可。這樣的控制代碼指向系統記憶體頁檔案。二.    對應檔檔案建立成功以後,以其返回的控制代碼作為參數,調用MapViewOfFile函數為記憶體對應檔對象建立視,MapViewOfFile函數將返回指向檔案的視指標。可以利用此視指標對記憶體對應檔進行操作,記憶體的讀寫簡化到了就像普通變數的操作。 下面是一個利用共有記憶體實現進程之間的資料共用的Sample程式。//寫記憶體程式 //MemWrite.cpp#include "stdafx.h"
#include "windows.h"
#include "iostream.h"class student
{
public:
 long ID;
 char name[20];
};void main()
{ HANDLE hMemShare; student stu;
    int stu_num = 30; student *lpstu; stu.ID = 99041232;
 strcpy(stu.name,"SecBug"); hMemShare = CreateFileMapping((HANDLE)0xFFFFFFFF,NULL,PAGE_READWRITE,0,sizeof(student),"TestMemShare"); if(hMemShare == NULL)
 {
  cout<<"Failed to Alloocate"<<endl;
  return;
 } lpstu = (student *)MapViewOfFile(hMemShare, FILE_MAP_WRITE,0,0,sizeof(student)); if(lpstu == NULL)
 {
  cout<<"Failed to Map"<<endl;
  return;  
 } *lpstu = stu; while(1){} UnmapViewOfFile(lpstu);
} //讀記憶體程式 // MemRead.cpp#include "stdafx.h"#include "windows.h"
#include "iostream.h"class student
{
public:
 long ID;
 char name[20];
};void main()
{ HANDLE hMemShare; student stu; student *lpstu; char *lpTch; stu.ID = 0; strcpy(stu.name ,"tst"); hMemShare = OpenFileMapping(FILE_MAP_READ,FALSE,"TestMemShare"); if(hMemShare == NULL)
 {  cout<<"File Created Failed"<<endl;  return;
 } lpstu = (student *)MapViewOfFile(hMemShare, FILE_MAP_READ,0,0,sizeof(student)); if(lpTch == NULL)
 {
  cout<<"Failed to Map"<<endl;
  return;
 } stu = *lpstu; cout<<stu.ID<<endl;
 cout<<stu.name<<endl; UnmapViewOfFile(lpstu);
} 二、共用記憶體實現進程間大資料的交換 

http://hi.baidu.com/bshetlyijuaflxr/item/c98bfef410e3c315fe358297

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.