On 14.03.2014 22:07, Fred van Stappen wrote:
 > It's not a problem, as long as you provide an API to dispose the memory
 > used by the returned PChar.
 > The responsibility of calling this API is delegated
 > to the application.

Yep, with pleasure,... but how to provide an API (and what do you mean
with "provide an API to dispose the memory") ?

=> In short, what must i code to do that ?

Inside your library you normally do this when creating a string result:

=== code begin ===

function InLibStringFunction: PChar; // of course declared as cdecl ;)
const
MyString: AnsiString = 'Hello World'; // this string could also come frome somewhere else in your library
begin
  Result := GetMem(Length(MyString) + 1);
  Move(@MyString[1], Result, Length(MyString));
  Result[Length(MyString)] := 0;
end;

=== code end ===

Note: if your MyString is valid through the complete lifetime it could be used you can also use "Result := PChar(MyString);" instead, but if your string is e.g. a variable inside the function or a variable inside another function you must copy its content.

If you now allocated a PChar using GetMem you add this function as well and export it from the library:

=== code begin ===

procedure InLibFreeString(aStr: PChar);
begin
  FreeMem(aStr);
end;

=== code end ===

One could of course now extend the API with additional checks. E.g. so that you know that the string was really allocated by the library and not by e.g. the program using it. But maybe the heap manager already checks this, I don't know currently.

Regards,
Sven
_______________________________________________
fpc-pascal maillist  -  fpc-pascal@lists.freepascal.org
http://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal

Reply via email to