How i can pass pchar from the DLL? dll must be compatible with other apps, not just delphi. In help is written that it is dangerous to pass pointers to local variables, if we make this variable global, the code will not be thread-safe.
We can safely pass a wide string,but in this case, the dll will not be compatible with other (non-Delphi) apps.
{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.