Delphi 内存映射实现两个进程间通信
程序员文章站
2023-12-22 16:28:16
...
写入方代码
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
PShareMem = ^TShareMem;
TShareMem = Record
id:string[8];
name:string[20];
age:Integer;
end;
type
TForm1 = class(TForm)
mmo1: TMemo;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
PShare: PShareMem;
HMapping: THandle;
shareMemName: string; //共享内存名
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
shareMemName:='GxMap';
//fillchar(pshare^, sizeof(TShareMem), 0); //初始化地址空间
//创建“内存映射文件”
hmapping:=CreateFileMapping($FFFFFFFF, nil, PAGE_READWRITE, 0, SizeOf(TShareMem), PChar(shareMemName));
if hmapping <> 0 then
begin
mmo1.Lines.Add('已成功创建内存映射文件!');
end;
//将“内存映射文件”与“应用程序地址空间”建立映射关系
pshare:=MapViewOfFile(hmapping,FILE_MAP_ALL_ACCESS,0,0,sizeof(TShareMem));
if pshare = nil then
begin
closehandle(hmapping);
mmo1.Lines.Add('映像映射失败!');
exit;
end
else
begin
mmo1.Lines.Add('成功建立!');
end;
pshare.id:='1';
pshare.name:='共享测试';
pshare.age:=18;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
//解除“内存文件”与“应用程序地址空间”的映射关系
if pshare<> nil then
UnmapViewOfFile(pshare);
//关闭内存映射文件
if hmapping<> 0 then
CloseHandle(hmapping);
end;
end.
读取方代码:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
PShareMem = ^TShareMem;
TShareMem = Record
id :string[8];
name:string[20];
age:Integer;
end;
type
TForm1 = class(TForm)
btn1: TButton;
mmo1: TMemo;
procedure btn1Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
HMapping : THandle;//内存映射文件句柄
shareMemName:string; //共享内存名
pUserShareMem : PShareMem;//指向共享内存的指针
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.btn1Click(Sender: TObject);
var
suser:string;
begin
shareMemName := 'GxMap'; //需要和创建的相同
HMapping := OpenFileMapping(FILE_MAP_ALL_ACCESS, false, pchar(shareMemName));
if HMapping <> 0 then
begin
mmo1.Lines.Add('打开内存映射文件')
end;
pUserShareMem := MapViewOfFile(HMapping, windows.FILE_MAP_ALL_ACCESS, 0, 0, sizeof(TShareMem));
if pUserShareMem <> nil then
begin
mmo1.Lines.Add('建立映射关系');
end;
if pUserShareMem <> nil then
begin
mmo1.Lines.Add( 'ID:' + pUserShareMem.id );
mmo1.Lines.Add( '姓名:' + pUserShareMem.name );
mmo1.Lines.Add( '年龄:' + IntToStr(pUserShareMem.age));
end;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
if pUserShareMem<> nil then
UnmapViewOfFile(pUserShareMem);
if HMapping<> 0 then
CloseHandle(HMapping);
end;
end.
最后效果:
如果用一个程序启动的另一个程序,可以如下传递参数,参数用空格分开‘1 2’
ShellExecute(Application.Handle, 'OPEN', PChar('..\Project2.exe'), '1 2', '', SW_SHOWNORMAL);
获取
ParamStr(0)//程序的带文件名的路径
ParamStr(1)//1
ParamStr(2)//2
推荐阅读