question about keeeping reference to toStringz()

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu May 31 01:23:27 UTC 2018


On Thursday, May 31, 2018 01:12:34 Dr.No via Digitalmars-d-learn wrote:
> On Wednesday, 30 May 2018 at 20:43:48 UTC, Ali Çehreli wrote:
> > On 05/30/2018 01:09 PM, Dr.No wrote:
> > > consider a C function with this prototype:
> > >> void foo(const char *baa);
> > >
> > > Does it means I should do:
> > >> string s = ...;
> > >> auto cstring = s.toStringz;
> > >> foo(cstring);
> > >
> > > rather just:
> > >> foo(s.toStringz);
> > >
> > > ?
> >
> > It depends. cstring method above is not sufficient if cstring's
> > life is shorter than the C library's use:
> >
> > void bar() {
> >
> >     string s = ...;
> >     auto cstring = s.toStringz;
> >     foo(cstring);
> >
> > } // <- cstring is gone
> >
> > What if the library saved that pointer while performing foo()?
> >
> > If cstring is in module-scope or in a container (e.g. an array)
> > that's in module-scope then it's fine. But then, you would have
> > to remove it from that container when the C library does not
> > need that pointer anymore.
> >
> > Ali
>
> is foo() is being called from a thread, how I am supposed to keep
> cstring "alive"?

If it's being passed to foo, then it should be on the stack until foo
returns, in which case, the GC should see it when it scans. It's when foo
could keep a reference to the pointer that you have a problem, since then as
soon as foo returns, the pointer you passed to foo won't be on the stack
anymore. So, in that case, you'd have to store the pointer somewhere in D
code so that the GC will see it when scanning.

Or are you concerned about something like spinning up a thread, calling foo,
and then exiting the thread while foo stores the pointer somewhere? If
that's the case, then you'll need to store the pointer in a shared or
__gshared variable in D code so that you can still refer to it after the
thread terminates.

- Jonathan M Davis




More information about the Digitalmars-d-learn mailing list