On Thursday, 31 May 2018 at 02:10:53 UTC, Mike Parker wrote:
On Thursday, 31 May 2018 at 01:12:34 UTC, Dr.No wrote:


is foo() is being called from a thread, how I am supposed to keep cstring "alive"?

As Jonathan explained, you don't have to worry about it if foo() itself doesn't assign the pointer to anything internally. That will be the case for most C functions. Well-behaved functions that need to keep the string around will copy it. That said, you need to be sure you understand fully what any C function you call is doing with the strings, or pointers to any memory allocated by the GC, that you pass to them.

In the rare cases where the C function does keep the pointer and you do need to keep a reference (if you don't have one already), the simplest approach is this one:

import core.memory;
GC.addRoot(cstring);

Then, when you no longer need it:
GC.removeRoot(cstring);

https://dlang.org/phobos/core_memory.html#.GC.addRoot

Actually thank you for this.

I had no idea you could do that with the GC.

Reply via email to