Using char* and C code

Jeremy DeHaan dehaan.jeremiah at gmail.com
Wed Mar 6 22:31:49 PST 2013


>> 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).


I actually wasn't sure if it was best to just append the 
character or use toStringz, but now that I know it does that I 
will always go with that function. I think I was going to ask 
that as well, but forgot or something.

> 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

Keeping a private member variable when using a class/struct was 
what I was thinking.  As for free functions, I was considering 
having the reference be a static variable inside the function, 
though I'm not sure how often I would need to do that in my port. 
The snippets of code I wrote were just to illustrate what I was 
talking about. I suppose I could have written a better example 
since most(if not all) of the wrapping of C functions are inside 
classes/structs. :P

Thanks for all the info though!






More information about the Digitalmars-d-learn mailing list