I have a DLL which provided a decoding function, as follows:
function MyDecode (Source: PChar; SourceLen: Integer; var Dest: PChar; DestLen: Integer): Boolean; stdcall;
The HostApp call "MyDecode", and transfer into the Source, SourceLen and Dest parameters, the DLL returns decoded Dest and DestLen. The problem is: The HostApp impossible to know decoded Dest length, and therefore would not know how to pre-allocated Dest's memory.
I know that can split "MyDecode" into two functions:
function GetDecodeLen (Source: PChar; SourceLen: Integer): Integer; stdcall; // Return the Dest's length
function MyDecodeLen (Source: PChar; SourceLen: Integer; var Dest: PChar): Boolean; stdcall;
But, My decoding process is very complicated, so if split into two functions will affect the efficiency.
Is there a better solution?
Yes Alexander, this may be a good solution. HostApp code:
//...
MyDecode(....)
try
// Use or copy Dest data
finally
FreeDecodeResult(...)
end;
DLL code:
function MyDecode(...): Boolean;
begin
// time-consuming calculate
// Allocate memory
GetMem(Dest, Size);
// or New()?
// or HeapAlloc()?
end;
procedure FreeDecodeResult(Dest: PChar);
begin
FreeMem(Dest);
// or Dispose(Dest); ?
// or HeapFree(Dest); ?
end;
Maybe I should change Dest's type to Pointer.
Which is a better allocate memory method? GetMem/New, or HeapAlloc?