[Lazarus] Bug on library project while accessing string
pascaldragon at googlemail.com
Sun Jan 27 12:03:09 CET 2013
On 24.01.2013 06:57, Darmawan Sugiarto wrote:
> hello guys, I got some bug on library project. When I uses Lazarus
> 0.9.28.2 I write this code and work well, then I recompile it use
> Lazarus 1.0.2 and 1.0.4 and got this error....
> Project project_test raised exception class 'External: SIGEGV'.
> At address 7C91B1FA
> I have 2 project
> first project is library project...
> Here is the code for first project
> function test(_str:string):string; cdecl; export;
Short answer: Don't use strings as arguments or result values if you
export a function from a library. Use PChar instead.
Long answer: Strings are so called "managed types". They involve
compiler magic which allocates the memory and frees it also if the
string is no longer needed. If you now have a library (let's assume both
are written with FPC) then you have two heap managers: one in the
program and one in the library. Those two don't know about each other
and thus if e.g. the program tries to free the string that your library
function returned that it will break, because it assumes the memory was
allocated by itself.
This can be solved in two (or in theory three) ways:
1. use PChar and manage the memory for your strings yourself (e.g. if
your library returns a PChar you need to have an additional exported
function with which you can tell your library to free the PChar's memory
again). Additional positive effect: the library can be written in
something else than FPC or the library can be used by a program not
written with FPC (other languages don't know FPC's String type).
[plattform specific note: on Windows (and there only!) you can use the
WideString type, because that type is managed by Windows]
2. use a common heap manager. If the heap manager is shared between the
program and the library than you can freely pass memory between both
parts and free it in the other part. For this you can use the unit
"cmem" which will use the C library's heap manager (works on Unix
systems, but should work on Windows ones as well). Note: the unit should
be the first unit used by your main file (the program file and the
(3. dynamic runtime packages allow you to freely pass strings (and also
object instances, etc.) between the program file and the package. As
Free Pascal does not support them yet this is only a theoretical option)
Additional note: Don't start a new question by answering to an existing
mail, because than your answer might not be seen by other mailing list
readers, because they might ignore the thread you posted to (as seems to
More information about the Lazarus