V Wed, 31 Dec 2014 11:19:35 +0000 Laeeth Isharc via Digitalmars-d-learn <digitalmars-d-learn@puremagic.com> napsáno:
> 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? First I am not sure, but you do not need to call fromStringz in this case. Next in this example you even not need to call toStringz, because D string literals are null-terminated. But generally it is better to use toStringz when need pass D strings to C code. 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.