我在做一个实验,目的是通过dll在程序之间传递字符数据,代码如下;
//dll的代码;
library Project1;
uses
windows;
{$R *.res}
var
hMem:Thandle;
function GetGlobalMem:Thandle;export;
begin
result:=hMem;
end;
exports
GetGlobalMem;
begin
hMem:=GLobalAlloc(gmem_MOVEABLE and gmem_DDEShare,1000);
if hMem=0 then
messagebox(getactivewindow(),'不能分配内存','结果',mb_ok);
end.
//服务程序的代码
..................
function GetGlobalMem:Thandle;export;external'project1.dll';
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
hMem:THandle;
pMem:Pchar;
begin
hMem:=GetGlobalMem;
if hMem<>0 then
begin
pMem:=GlobalLock(hMem);
if pMem<>nil then
begin
strPCopy(pMem,Memo1.Text);
GlobalUnlock(hMem);
end
else
showmessage('出错!');
end;
end;
//客户程序的代码:
..................
function GetGlobalMem:Thandle;export;external'D:\dll-service\project1.dll';
//与服务程序调用同一个dll;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
hMem:THandle;
pMem:Pchar;
begin
hMem:=GetGlobalMem;
if hMem<>0 then
begin
pMem:=GlobalLock(hMem);
if pMem<>nil then
begin
Memo1.Text:=strPas(pMem);
GlobalUnlock(hMem);
end
else
showmessage('出错');
end
end;
end.
我先运行服务程序在其memo1中输入"132143"点击服务程序的button1;然后我再运行客户程序点击button1,在客户程序的memo1.text中显示"x";
后来不管在服务程序的memo1中输入什么内容,在客户程序的memo1.text中只显示"x";即使我只运行客户程序也只显示"x";
真不知道是为什么?请大家帮看看!
//dll的代码;
library Project1;
uses
windows;
{$R *.res}
var
hMem:Thandle;
function GetGlobalMem:Thandle;export;
begin
result:=hMem;
end;
exports
GetGlobalMem;
begin
hMem:=GLobalAlloc(gmem_MOVEABLE and gmem_DDEShare,1000);
if hMem=0 then
messagebox(getactivewindow(),'不能分配内存','结果',mb_ok);
end.
//服务程序的代码
..................
function GetGlobalMem:Thandle;export;external'project1.dll';
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
hMem:THandle;
pMem:Pchar;
begin
hMem:=GetGlobalMem;
if hMem<>0 then
begin
pMem:=GlobalLock(hMem);
if pMem<>nil then
begin
strPCopy(pMem,Memo1.Text);
GlobalUnlock(hMem);
end
else
showmessage('出错!');
end;
end;
//客户程序的代码:
..................
function GetGlobalMem:Thandle;export;external'D:\dll-service\project1.dll';
//与服务程序调用同一个dll;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
hMem:THandle;
pMem:Pchar;
begin
hMem:=GetGlobalMem;
if hMem<>0 then
begin
pMem:=GlobalLock(hMem);
if pMem<>nil then
begin
Memo1.Text:=strPas(pMem);
GlobalUnlock(hMem);
end
else
showmessage('出错');
end
end;
end.
我先运行服务程序在其memo1中输入"132143"点击服务程序的button1;然后我再运行客户程序点击button1,在客户程序的memo1.text中显示"x";
后来不管在服务程序的memo1中输入什么内容,在客户程序的memo1.text中只显示"x";即使我只运行客户程序也只显示"x";
真不知道是为什么?请大家帮看看!
想全局必须用MappingFile
能不能具体讲一讲MappingFile的用法!谢谢
OpenFileMapping()
MapViewOfFile()
UnmapViewOfFile()
网上查一下