On Fri, 04 Apr 2014 09:25:49 -0400, Marc Schütz <schue...@gmx.net> wrote:
On Wednesday, 2 April 2014 at 16:51:57 UTC, Benjamin Thaut wrote:
Am 02.04.2014 17:57, schrieb Andrea Fontana:
I mean: if it is an exported function (of a shared library) what
happens? There's no reference kept anywhere (in D). So if I'm right it
could be freed immediatly by GC. Right?
If you pass that string to a C function, there is a reference on the
stack. So this string will not be freed until that C-function returns.
If that C-Function returns, it is very likely however that this was the
only reference and the string will be freed the next time the garbage
collector runs.
This is unfortunately only true on x86 32-bit. For x86_64, the calling
conventions (MS, SysV [1]) say that the first few parameters are passed
in registers, and the same is probably true for other architectures.
Usually this is still safe, as the pointer will normally either stay in
its register, or will be spilled to the stack and kept there as long as
the function still needs to use it. But one might imagine a corner case
where it temporarily stores the pointer in a global or static variable.
Even if the pointer will not be kept by the C function longer than the
call, in such cases you would need to keep an additional reference where
the GC can see it.
In cases where it is stored in global data, and that becomes the only
reference, or if a C heap allocation is made, and the pointer is stored in
there (perhaps to pass to another C function?), then it's quite possible
the data could be collected prematurely in another thread.
You bring up a good point. This is something that should be considered
when calling extern(C) functions.
-Steve