类似横山少佐的男主:利用内存映射文件在两个进程间共享数据

来源:百度文库 编辑:中财网 时间:2024/05/05 08:52:19

利用内存映射文件在两个进程间共享数据

分类: Delphi 2008-10-03 13:04 366人阅读 评论(0) 收藏 举报
  1.   private
  2.     hMapFile: THandle;
  3.     MapFilePointer: Pointer;
  4.   public
  5.     { Public declarations }
  6.   end;
  7. var
  8.   Form1: TForm1;
  9. implementation
  10. {$R *.DFM}
  11. procedure TForm1.FormCreate(Sender: TObject);
  12. begin
  13.   hMapFile := CreateFileMapping (
  14.     $FFFFFFFF, // 特殊内存映射句柄
  15.     nil, page_ReadWrite, 0,10000,
  16.     'DdhDemoMappedFile'); // 文件名
  17.   if hMapFile <> 0 then
  18.     MapFilePointer := MapViewOfFile (
  19.       hMapFile, // 上面映象文件的句柄
  20.       File_Map_All_Access,
  21.       0, 0, 0) // 访问整个映象文件
  22.   else
  23.     ShowMessage ('hMapFile = 0');
  24.   if MapFilePointer = nil then
  25.     ShowMessage ('MapFilePointer = nil');
  26. end;
  27. procedure TForm1.BtnWriteClick(Sender: TObject);
  28. begin
  29.   StrCopy (PChar (MapFilePointer),
  30.     PChar (EditWrite.Text));//把内容写入共享内存
  31. end;
  32. procedure TForm1.BtnReadClick(Sender: TObject);
  33. var
  34.   S: string;
  35. begin
  36.   S := PChar (MapFilePointer);//从共享内存读出内容
  37.   EditRead.Text := S;
  38. end;

用这种方法,不但可以在不同的程序之间共享数据,还可以
在同一程序的不同实例间共享数据。为了及时通知其它进程
共享数据的变化,可以自定义一条用户消息,通过发消息来
实现。