[fpc-devel] Access Violation with nested DLL'scompiledbyFPC(andsome more info on bug #4538)

Marc Weustink marc.weustink at cuperus.nl
Wed Dec 14 18:44:31 CET 2005


L505 wrote:
>>The reference count is part of the ansistring itself. An ansistring
>>is simply a pointer to a record containing a reference count, the
>>amount of memory currently allocated for the string (i.e., maximum
>>length -1) and the string itself (a 0-terminated string).
>>
>>So when passing a string from a dll to somewhere else, its reference
>>count is passed along with it.
>>
> 
> 
> Instead of asking all the newbie questions, I will do more reading about reference
> count science on my own too.. but if it's easy for you to tell me here, how does the
> reference count know ahead of time that there will be no usage of the string when it
> sets the reference count to 0? i.e. how is the reference count decremented? Does the
> compiler know this at compile time?


In short (don't pin me on the names or on exact details in special cases):

Assume you have a ansistring and you assign something to it

   S := 'SomeString';

the compiler generates something like

   DecStringRef(S);
   S -> 'SomeString';
   IncStringRef(S);

The DecStringRef() decrements the refcount and checks if the it reaches 
zero. Ifso, the string is freed. The referencecounter of a strings lies 
in memory just before the actual text. Thats why you cannot pass a @S to 
a procedure which expects a textbuf. In that case you pass @S[1], the 
adress of the first character.

THis decrefcount is also the reason that you shouldn't pass strings to a 
dll. Suppose the string is created in your main app en passed to a dll. 
As soon as a DecStringRef is called (and the reference reaches 0) the 
code executes in your dll, So the freeing of the string is also done in 
the dll (and a free memblock is added to the dll instead of the app)

Marc





More information about the fpc-devel mailing list