有关dll的返回值问题(pchar型),为何出错?(100分)

N

Nstar

Unregistered / Unconfirmed
GUEST, unregistred user!
主程序中的dll调用函数:
function LoadInputDll(DllName, funName: string):pchar;
Type
TFormSample=function :pchar;
var
hDll:THandle;
SampForm:TFormSample;
fn,s:string;
begin
//从数据库中取得DLL文件的信息
//GetDllInformation;
fn:=DllName;
Result:='';
if FileExists(fn)=False then
begin
s:='动态链接库文件 "'+fn+'" 丢失!请重新下载!'+#13#10;
s:=s+'下载后拷贝到 "'+ExtractFilePath(Application.ExeName)+'DLL/" 目录下。';
ShowMessageOne(s);
Result:='';
exit;
end else
begin
hDll:=LoadLibrary(Pchar(fn));
if hDll<>0 then
begin
try
@sampForm:=GetProcAddress(hDll,Pchar(funName));
if @sampForm<>nil then
begin
Result:=SampForm;
end else
MessageDlg('加载函数 "'+funName+'" 出现错误 !',mtError,[mbOk],0);
finally
FreeLibrary(hDLL);
end;
end else
MessageDlg('调用动态链接库 "'+DllName+'" 错误!',mtError,[mbOk],0);
end;
end;
==============================================
dll中函数:
function ShowInput:pchar;stdcall;
var
ipt:TfrmInputForm;
begin
Application.CreateForm(TfrmInputForm, ipt);
with iptdo
begin
if ShowModal=mrOk then
begin
result:=Pchar(txtInput.Text);
end
else
Result:='';
Free;
end;
end;
=======================================
我是将输入对话框做成dll返回,由dll返回输入的值,但是取返回值总是报错,这是为何?
我在调用LoadInputDll时返回对话框输入的值总是出错!
 
可以直接用string传参数
---
http://www.8421.org
 
这样改试一试:
function ShowInput:pchar;stdcall;
var
ipt:TfrmInputForm;
begin
with TfrmInputForm.Createdo
begin
if ShowModal=mrOk then
begin
result:=Pchar(txtInput.Text);
end
else
Result:='';
Free;
end;
end;
 
当然不行了,你在ShowInput中已经把ipt Free掉了,但你的返回值实际上却是ipt上的
txtInput.Text属性的PChar,也就是说,你返回值的指针实际上是指向一块已经Free的内存,
不出错才奇怪了。
 
多人接受答案了。
 
顶部