returning D string from C++?

bitwise via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Aug 6 10:16:05 PDT 2017


On Sunday, 6 August 2017 at 16:46:40 UTC, Mike Parker wrote:
> On Sunday, 6 August 2017 at 16:23:01 UTC, bitwise wrote:
>
>> So I guess you're saying I'm covered then? I guess there's no 
>> reason I can think of for the GC to stop scanning at the 
>> language boundary, let alone any way to actually do that 
>> efficiently.
>
> It's not something you can rely on. If the pointer is stored in 
> memory allocated from the C heap, then the GC will never see it 
> and can pull the rug out from under you. Best to make sure it's 
> never collected. If you don't want to keep a reference to it on 
> the D side, then call GC.addRoot on the pointer. That way, no 
> matter where you hand it off, the GC will consider it as being 
> live. When you're done with it, call GC.removeRoot.

I was referring specifically to storing gc_malloc'ed pointers on 
the stack, meaning that I'm calling a C++ function on a D call 
stack, and storing the pointer as a local var in the C++ function 
before returning it to D.

The more I think about it, the more I think it has to be ok to 
do. Unless D stores [ESP] to some variable at each extern(*) 
function call, then the GC would have no choice but indifference 
as to what side of the language boundary it was scanning on. If 
it did, I imagine it would say so here:

https://dlang.org/spec/cpp_interface.html#memory-allocation


More information about the Digitalmars-d-learn mailing list