进程间共享内存资源的问题~
代码如下,功能是,当运行两个程序时,第二个程序的Edit1,Edut2 得到文件映射对象的句柄和记录在共享内存里面的数据。不明白的地方时,当记录程序的句柄有效,而当想记录字符串类型,运行第2个程序不能得到记录的字符串,请前辈们指点。谢谢~
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
const
MapFileName = '{CAF49BBB-AF40-4FDE-8757-51D5AEB5BBBF}';
type
TForm1 = class(TForm)
edt1: TEdit;
edt2: TEdit;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
type
//共享内存
PShareMem = ^TShareMem;
TShareMem = record AppHandle: THandle; //保存程序的句柄
//str:string ;
end;
var
Form1: TForm1;
hMapFile: THandle;
PSMem: PShareMem;
implementation
{$R *.dfm}
procedure CreateMapFile;
begin
hMapFile := OpenFileMapping(FILE_MAP_ALL_ACCESS, False, PChar(MapFileName));
if hMapFile = 0 then
begin
hMapFile := CreateFileMapping($FFFFFFFF, nil, PAGE_READWRITE, 0,SizeOf(TShareMem), MapFileName);
PSMem := MapViewOfFile(hMapFile, FILE_MAP_WRITE or FILE_MAP_READ, 0, 0, 0);
//PSMem^.str := 'ni hao' ;
PSMem^.AppHandle := Application.Handle ;
end
else
begin
PSMem := MapViewOfFile(hMapFile,FILE_MAP_ALL_ACCESS, 0, 0, 0);
end;
Form1.edt1.Text := IntToStr(hMapFile );
//Form1.edt2.Text := PSMem^.str ;
Form1.edt2.Text := IntToStr(PSMem^.AppHandle );
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
CreateMapFile ;
end;
procedure FreeMapFile;
begin
UnMapViewOfFile(PSMem);
CloseHandle(hMapFile );
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
FreeMapFile ;
end;
end.