Garbage collector returning pointers

via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Mar 15 08:57:43 PDT 2015


On Sunday, 15 March 2015 at 15:08:43 UTC, Robert M. Münch wrote:
> On 2015-03-14 20:45:21 +0000, Marc Schütz said:
>
>> As long as the pointer remains on the stack or in a register, 
>> the GC will keep the allocation alive.
>
> Hi Marc, ok, got it. Thanks.
>
>> But if your C code stores the pointer on the C heap or in a 
>> global, the GC won't know anything about it and can free it.
>
> Ok. I need to dig into how the interpreter handles the returned 
> pointer and how the stack is handled.

C usually uses manual memory management, therefore I would expect 
that the interpreter actually documents whom the pointer belongs 
to, and who is responsible for cleaning it up.

If the interpreter takes ownership, you should just allocate the 
data with malloc(), and the interpreter will then call free() on 
it when it doesn't need it any longer. Not sure whether .dup is 
compatible with that, maybe you'd need to write a small helper 
that copies things to the C heap.

Otherwise, maybe the interpreter will call you back when it wants 
to free the memory.

In both cases, you don't need to use GC pointers at all, because 
it's actually doing manual memory management.


More information about the Digitalmars-d-learn mailing list