[fpc-pascal] fp libraries do not like cmem ?

Ewald ewald at yellowcouch.org
Fri Feb 14 20:51:53 CET 2014


On 14 Feb 2014, at 20:28, Fred van Stappen wrote:

> >What I have been wondering for some time now (perhaps you wrote it in a
> >mail and I missed it): do you use the same memory manager in the library
> >and in your test program?
> 
> Oops, indeed i forget that point...
> The test now are with cmem only in program, not in library.
> 
> I will test with cmem into library too...

That that is issue number 1: if your program wants to free something that your library allocated, both operations need to be done by the same memory manager.

> 
> >The example here might be extremely over-simplified, but replace
> > `a: Integer` with `mystring: String` and we're roughly at your example.
> 
> Hum, absolutely, it is the same example... 
> So, how must i do to use PChar ?

The way I use to pass strings from C/C++ libraries is to allocate a buffer, copy the contents of the string into the buffer and return the pointer to that buffer. The same method can be used here. Also don't forget to provide a second function to free these buffers (in this way your library can have a different memory manager than your application).

So you might try something along the lines of:

Function ConvertToPChar(str: String): PChar;
Begin
	Result:= Getmem(Length(str) + 1);	// Allocating the buffer somewhere on the heap

	If Length(str) > 0 Then
		Move(str[1], Result[0], Length(str));	// The content
	
	Result[l]Length(str)]:= #0;	// The null termination
End;

..., where I decided to return `standard` null-terminated strings, since your library is meant to be `universal`.

Next, the procedure to free buffers using the memory manager of the library:

Procedure FreeBuffer(Buffer: Pointer);
Begin
	FreeMem(Buffer);
End;

That's it for the library part. In your program part, don't forget to free these buffers once they are no longer needed.

Also note that this is a good approach with respect to `universiality`, but if you need to pass a lot of strings to and fro you would be better off with a more pascalish version. The thing that comes to mind here is providing a function in your library that replaces the current memory manager with the one passed to it as an argument. This would allow you to simply return a string.

--
Ewald

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20140214/cc3a1de4/attachment.html>


More information about the fpc-pascal mailing list