问题:一个函数
Type TMyDLLFunc=function():wideString;stdcall;Function func1:boolean;
var
H_inst:THandle;
MyFPointer:Pointer;
MyFunc:TMyDLLFunc;
begin
H_inst:=LoadLibrary('mydll.dll');
if H_inst=0 then
begin
showmessage('加载动态库失败!');
Result:=false;
end
else if H_inst>0 then
begin
try
MyFPointer:=GetProcAddress(H_inst,pchar('mydllfunc'));
if MyFPointer<>nil then
begin
MyFunc:=TMyDLLFunc(MyFPointer);
if MyFunc<>'' then
begin
showmessage(myfunc);
Result:=False;
end
else Result:=True;
end;
finally
FreeLibrary(H_inst);
end;
end;
end;
在窗体中调用的时候:
procedure TForm1.FormCreate(Sender: TObject);
begin
if func1 then showmessage('ok');
otherfucn;//这里是其它的过程或函数,在这里出现了 Access violation错误,我怀疑是由于func1里指针导致的,可是找不到原因,求解
end;
Type TMyDLLFunc=function():wideString;stdcall;Function func1:boolean;
var
H_inst:THandle;
MyFPointer:Pointer;
MyFunc:TMyDLLFunc;
begin
H_inst:=LoadLibrary('mydll.dll');
if H_inst=0 then
begin
showmessage('加载动态库失败!');
Result:=false;
end
else if H_inst>0 then
begin
try
MyFPointer:=GetProcAddress(H_inst,pchar('mydllfunc'));
if MyFPointer<>nil then
begin
MyFunc:=TMyDLLFunc(MyFPointer);
if MyFunc<>'' then
begin
showmessage(myfunc);
Result:=False;
end
else Result:=True;
end;
finally
FreeLibrary(H_inst);
end;
end;
end;
在窗体中调用的时候:
procedure TForm1.FormCreate(Sender: TObject);
begin
if func1 then showmessage('ok');
otherfucn;//这里是其它的过程或函数,在这里出现了 Access violation错误,我怀疑是由于func1里指针导致的,可是找不到原因,求解
end;
如果两个函数声明的确都是 function():wideString;stdcall; 而且这个函数本身没问题的话,那错误就不是由它引发的
Type TMyDLLFunc=function(var buf: Pchar):Byte;stdcall;
外部去申请内存,用完外部在释放掉。这样的内存在你调用的地方使用GetMem动态分配,将动态分配的PChar变量传给调用你的Dll函数,Dll函数会操作Pchar变量,得到你要的结果,用完后,你对该变量进行你需要的处理,处理完后,FreeMem掉分配的内存。(要长久的持有这个结果,你可以在FreeMem前的处理过程中,将PChar存储的内容取出来放到一个可以长久持有的变量中,eg Delphi的String类型变量中)。
可以参考:http://www.delphibbs.com/keylife/iblog_show.asp?xid=26977
MyFPointer: TMyDLLFunc;
MyFunc: WideString; MyFPointer := TMyDLLFunc(GetProcAddress(H_inst,pchar('mydllfunc')));
if MyFPointer<>nil then
begin
MyFunc := MyFPointer();
if MyFunc<>'' then