再问一个问题:
我在主程序中给变参分配空间,为什么在DLL中释放的时候会出错?
主程序:
//在函数内分配空间
function GetIniFile2(var s
Char):boolean;stdcall;
var
sIni:string;
begin
sIni := GetDefaultIniName;
s := StrNew(PChar(sIni));
result := true;
end;
//在DLL中分配空间
function GetTitle(var s
Char;iLength:integer):boolean;stdcall;
var
sTitle:string;
begin
if assigned(MainForm.CurrentChild) then
begin
sTitle := MainForm.CurrentChild.Caption;
if iLength < Length(sTitle) then
begin
result := false;
exit;
end;
strlcopy(s,PChar(sTitle),Length(sTitle));
result := true;
end
else
result := false;
end;
//在函数内分配空间
function GetText2(var s
Char;iLength:integer):boolean;stdcall;
begin
if assigned(MainForm.CurrentChild) then
begin
s := strnew(PChar(MainForm.CurrentChild.Editor.Lines.Text));
result := true;
end
else
result := false;
end;
DLL中的调用:
var
iLength:integer;
sText
Char;
sTitle
Char;
sIni
Char;
bResult :boolean;
begin
bResult := TGetString2(GetProcAddress(AOwner,'GetIniFile2'))(sIni);
if not bResult then
begin
StrDispose(sIni);
exit;
end;
GetMem(sTitle,256);
bResult := TGetString(GetProcAddress(AOwner,'GetTitle'))(sTitle,255);
if not bResult then
begin
StrDispose(sIni);
FreeMem(sTitle);
exit;
end;
bResult := TGetString2(GetProcAddress(AOwner,'GetText2'))(sText);
if not bResult then
begin
StrDispose(sIni);
FreeMem(sTitle);
StrDispose(sText);
exit;
end;
//sIni,sText,sTitle的值都是正确的。
StrDispose(sIni);//出错,invalid pointer operation
StrDispose(sText);
FreeMem(sTitle);
end;
但是如果把
bResult := TGetString2(GetProcAddress(AOwner,'GetText2'))(sText);
if not bResult then
begin
StrDispose(sIni);
FreeMem(sTitle);
StrDispose(sText);
exit;
end;
去掉,也就是说不给sText分配内存,StrDispose(sIni)就正常,难道两次分配
内存有相关性?