我如何从 DLL 传递 pchar?dll 必须与其他应用程序兼容,而不仅仅是 delphi。帮助中写道,将指针传递给局部变量是危险的,如果我们将此变量设为全局变量,代码将不是线程安全的。
我们可以安全地传递一个宽字符串,但在这种情况下,dll 将与其他(非 Delphi)应用程序不兼容。
{code in dll}
function Test:pchar;
var
str:string;
begin
str:='Some string';
result:=pchar(str); // wrong way, may be UB.
end;
{code in dll}
var
str:string // global variable
function Test:pchar;
begin
str:='Some string';
result:=pchar(str); // code not threadsafe
end;
{code in dll}
function Test:WideString;
var
str:WideString;
begin
str:='Some string';
result:=str; // will works ONLY with Delphi apps :(
end;
:(
how do experienced programmers?
var
Form1: TForm1;
function Test(out p:pchar):Integer;stdcall; external 'project2';
procedure FinalizeStr(P:Pointer);stdcall; external 'project2';
implementation
{$R *.dfm}
function StrFromDll:string;
var
p:pchar;
begin
try
setstring(result,P, test(p));
finally
finalizestr(cardinal(p));
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
showmessage(strfromdll);
end;
{code in dll}
library Project2;
uses
fastmm4,fastmm4messages,
SysUtils,
Classes;
{$R *.res}
function Test(out p:pchar):Integer;stdcall;
var
str:string;
len:integer;
begin
str:='Hello, i am a string from the dll?!#@%!?'+inttostr(hinstance); // only for example
len:=length(str);
p:=allocmem(len+1);
StrPLCopy(P,str,len);
result:=len;
end;
procedure FinalizeStr(P:Pointer);stdcall;
begin
FreeMem(P);
end;
exports Test,FinalizeStr;
end.