进程间通信可以使用内存映射文件;
在dll中共享数据可以使用内存映射文件
{*******************************************************}
{ }
{ 内存映射文件 }
{ }
{ 版权所有 (C) 2010 zhaoh }
{ }
{*******************************************************}
unit unMapfile;
interface
uses
Windows,
SysUtils;
type
EMapCreateError =class(Exception);
EMapViewError=class(Exception);
{ TMapFile }
TMapFile=class
private
hMapFile:THANDLE;
pMemeory:Pointer;
procedure MapFile;
public
{-------------------------------------------------------------------------------
过程名: Create ,创建一个内存映射文件
作者: Administrator
日期: 2010.01.27
参数: Size:DWORD; 内存映射文件的大小
Name:string; 映射文件大小
FileHandle:THandle=INVALID_HANDLE_VALUE 文件句柄, 默认是内存映射文件,可以把文件映射到内存,
返回值: 无
-------------------------------------------------------------------------------}
constructor Create(Size:DWORD; Name:string;FileHandle:THandle=INVALID_HANDLE_VALUE);overload;
{-------------------------------------------------------------------------------
过程名: Create 打开一个已经存在的内存映射文件
作者: Administrator
日期: 2010.01.27
参数: Name:string
返回值: 无
-------------------------------------------------------------------------------}
constructor Create(Name:string); overload;
destructor Destroy; override;
property MemoryPointer:Pointer read pMemeory;
end;
implementation
{ TMapFile }
constructor TMapFile.Create(Size:DWORD; Name:string;FileHandle:THandle=INVALID_HANDLE_VALUE);
begin
inherited Create;
hMapFile:=CreateFileMapping(FileHandle,nil,PAGE_READWRITE,0,Size,PChar(Name));
if hMapFile=0 then
raise EMapCreateError.Create('');
MapFile;
end;
constructor TMapFile.Create(Name: string);
begin
inherited Create;
if SameText(Name,'') then
raise EMapCreateError.Create('');
hMapFile:=OpenFileMapping(FILE_MAP_ALL_ACCESS,False,PChar(Name));
if hMapFile=0 then
raise EMapCreateError.Create('');
MapFile;
end;
destructor TMapFile.Destroy;
begin
if pMemeory <> nil then
UnmapViewOfFile(pMemeory);
if hMapFile<>0 then
CloseHandle(hMapFile);
inherited;
end;
procedure TMapFile.MapFile;
begin
pMemeory:=MapViewOfFile(hMapFile,FILE_MAP_ALL_ACCESS,0,0,0);
if pMemeory=nil then
begin
raise EMapViewError.Create('');
end;
end;
end.
使用方法
try
tmf:=TMapFile.Create('光军之城');
except
tmf:=TMapFile.Create(100,'光军之城');
end;