两个程序 通过共享内存 传递数据 CreateFileMapping

QmyShareMem=record
name:array[0..20] of Char;
birthday:TDateTime;
note:array[0..50] of Char;
end;


{程序一 创建 共享内存}
procedure TForm1.Button2Click(Sender: TObject);
var
hFileMapping:THandle;
begin
hFileMapping:=openfilemapping(File_MAP_ALL_ACCESS,False,PChar('ftwsnow'));
if hFileMapping=0 then
begin
hFileMapping:=CreateFileMapping($FFFFFFFF,nil,PAGE_READWRITE,0,SizeOf(QmyShareMem), PChar('ftwsnow'));
{内存映射的话,第一个参数必须是$FFFFFFFF,文件映射的话就是文件句柄
第二个参数:安全,一般为nil
第三个参数:映射文件的属性,我们要可读可写
第四个参数:要映射数据大小的高4个字节
第五个参数:要映射数据大小的低4个字节
第六个参数:唯一的名字
}
if hFileMapping = 0 then
raise Exception.Create('CreateFileMapping failed with error code '+ IntToStr(GetLastError));
end;
end;



{程序1 读 共享内存 并赋值 }
procedure TForm1.Button1Click(Sender: TObject);
var
hFileMapping:THandle;
cc:QmyShareMem;
DataPointer:Pointer;
begin
DataPointer:=nil;
hFileMapping:=openfilemapping(File_MAP_ALL_ACCESS,False,PChar('ftwsnow'));
if hFileMapping<>0 then
begin
DataPointer:=MapViewOfFile(hFileMapping,FILE_MAP_ALL_ACCESS,0,0,SizeOf(QmyShareMem));
if DataPointer = nil then
raise Exception.Create('MapViewOfFile failed with error code ' +IntToStr(GetLastError));
FillChar(cc,SizeOf(cc),#0);
cc.name:='安南秀';
cc.birthday:=Now;
cc.note:='Have a nice day~!;
copymemory(DataPointer,@cc,SizeOf(cc)); {给共享内存赋值}
end;
end;



{程序二 读 共享内存}
procedure TForm1.Button1Click(Sender: TObject);
var
datapointer:Pointer;
hFileMapping:THandle;
begin
hFileMapping:=openfilemapping(File_MAP_ALL_ACCESS,False,PChar('ftwsnow'));
if hFileMapping<>0 then
begin
datapointer:=nil;
DataPointer:=MapViewOfFile(hFileMapping,FILE_MAP_ALL_ACCESS,0,0,SizeOf(qmysharemem));
if datapointer<>nil then
ShowMessage(qmysharemem(DataPointer^).name+DateTimeToStr(qmysharemem(DataPointer^).birthday));
end;
end;



{程序二 写 共享内存}
procedure TForm1.Button2Click(Sender: TObject);
var
datapointer:Pointer;
hFileMapping:THandle;
begin
hFileMapping:=openfilemapping(File_MAP_ALL_ACCESS,False,PChar('ftwsnow'));
if hFileMapping<>0 then
begin
datapointer:=nil;
DataPointer:=MapViewOfFile(hFileMapping,FILE_MAP_ALL_ACCESS,0,0,SizeOf(qmysharemem));
if datapointer<>nil then
begin
qmysharemem(DataPointer^).name:='李半妆';
ShowMessage(qmysharemem(DataPointer^).name+DateTimeToStr(qmysharemem(DataPointer^).birthday));
end;
end;
end;

 

你可能感兴趣的:(mapping)