[fpc-pascal] Library.StringFunction() : PChar => NO
Fred van Stappen
fiens at hotmail.com
Fri Mar 14 23:45:39 CET 2014
> Date: Fri, 14 Mar 2014 23:11:14 +0100
> From: pascaldragon at googlemail.com
> To: fpc-pascal at lists.freepascal.org
> Subject: Re: [fpc-pascal] Library.StringFunction() : PChar => NO
>
> 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
Yep, Sven, excellent and hyper clear.
Hum, i think that this code must go somewhere in wiki.
If you agree i will add it into fpc wiki.
Many thanks.
Fred.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20140314/4021cfa7/attachment.html>
More information about the fpc-pascal
mailing list