C string to D without memory allocation?
Jakob Ovrum via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Dec 21 00:45:32 PST 2015
On Monday, 21 December 2015 at 08:35:22 UTC, Jonathan M Davis
wrote:
> There's also fromStringz that Jakob suggests using elsewhere in
> this thread, but that really just boils down to
>
> return cString ? cString[0 .. strlen(cString)] : null;
>
> So, using that over simply slicing is primarily for
> documentation purposes, though it does make it so that you
> don't have to call strlen directly or check for null before
> calling it.
To add to this, the main motivation behind `fromStringz` is that
`cString` is often a non-trivial expression, such as a function
call. With `fromStringz`, this expression can always be put in
the argument list and it will only be evaluated once. Otherwise a
variable has to be added:
auto cString = foo();
return cString[0 .. strlen(cString)];
More information about the Digitalmars-d-learn
mailing list