Using char* and C code

Jeremy DeHaan dehaan.jeremiah at gmail.com
Wed Mar 6 21:58:23 PST 2013


Hey guys!

Today while browsing std.string, I read this:

Important Note: When passing a char* to a C function, and the C 
function keeps it around for any reason, make sure that you keep 
a reference to it in your D code. Otherwise, it may go away 
during a garbage collection cycle and cause a nasty bug when the 
C code tries to use it.

Good to know! Now, I have seen things like this before.

extern (C) void someCFunction(const(char)* stuff);

void main()
{
      someCFunction("string!");
}

I know that string literals implicitly cast to this type and even 
have the '\0' at the end, but couldn't this cause the bug 
described above?

I'm currently working on a port of a C library into D, so I'm 
trying to have the end user avoid using pointers all together. I 
might write the above code as something like:

void someFunction(string stuff)
{
      stuff ~= "\0";
      someCFunction(stuff.ptr);
}

But that was before I read the warning! Obviously if I know 100% 
that the C function doesn't keeps a copy of this pointer the 
above would be ok to do. I already had some ideas on how to deal 
with this, but I was wondering what other people have done. Do 
you just make some place holder string variable to make sure it 
won't get GC'd? Or is there a more elegant way?


More information about the Digitalmars-d-learn mailing list