Passing string literals to C

Gary Willoughby via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jan 1 07:06:05 PST 2015


On Wednesday, 31 December 2014 at 11:19:36 UTC, Laeeth Isharc 
wrote:
> Argh - no way to edit.
>
> What's best practice here?
>
> D strings are not null-terminated.
> ===
> cpling.c
>
> char* cpling(char *s)
> {
>   s[0]='!';
>   return s;
> }
> ===
> dcaller.d
>
> extern(C) char* cpling(char* s);
>
> void callC()
> {
>   writefln("%s",fromStringz(cpling("hello\0")));
> }
>
> or
>
> void callC()
> {
>   writefln("%s",fromStringz(cpling(toStringz("hello"))));
> }
>
> ===
>
> am I missing a better way to do this?

To call a C function you can either use string literals which are 
always null terminated or use std.string.toStringz (when using 
string variables) to add the null and return a char*.

To convert from char* (from a C function return value) to a D 
string use std.conv.to!(string).


More information about the Digitalmars-d-learn mailing list