From the D Blog -- Interfacing D with C: Strings Part One

Mike Parker aldacron at gmail.com
Tue May 25 00:38:28 UTC 2021


On Monday, 24 May 2021 at 16:16:53 UTC, Steven Schveighoffer 
wrote:

>
> Nice article!

Thanks!

>
> Note that there is a huge pitfall awaiting you if you use 
> `toStringz`: garbage collection. You may want to amend the 
> article to identify this pitfall.
>
> And I'm not talking about requiring `@nogc`, I'm talking about 
> the GC collecting the data while C is still using it.
>
> In your example:
>
> ```d
> puts(s1.toStringz());
> ```
>
> This leaves a GC-collectible allocation in C land. For `puts`, 
> it's fine, as the data is not used past the call, but in 
> something else that might keep it somewhere not accessible to 
> the GC, you'll want to assign that to a variable that lasts as 
> long as the resource is used.
>

That's what I'm referring to in the conclusion where I say this 
about what's going to be in Part Two:

> how to avoid a potential problem spot that can arise when 
> passing GC-allocated D strings to C

I'll cover approaches to maintaining a reference, like 
`GC.addRoot`, and emphasize that it applies to any GC-allocated 
memory, not just strings.





More information about the Digitalmars-d-announce mailing list