Using char* and C code

Jonathan M Davis jmdavisProg at gmx.com
Wed Mar 6 22:13:26 PST 2013


On Thursday, March 07, 2013 06:58:23 Jeremy DeHaan wrote:
> 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);
> }

That's what toStringz is for, and it'll avoid appending the '\0' if it can 
(e.g. if the code unit one past the end of the string is '\0' as it is with 
string literals).

> 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?

Very few C functions will keep the strings around, but if you think that 
there's a possibility that they will, then you'll need to keep a reference to 
the char* that you're passing in. If you're dealing with a class or struct, 
then that's as simple as having a member variable for it, but if you're 
dealing with free functions, that's likely to mean that whoever is using those 
functions is going to have to worry about it. And since string literals are 
part of the program itself, you shouldn't need to worry about keeping 
references to those. They should exist for the duration of the program.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list