C string to D without memory allocation?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Dec 21 00:35:22 PST 2015


On Monday, December 21, 2015 18:39:32 Rikki Cattermole via Digitalmars-d-learn wrote:
> size_t strLen = ...;
> char* ptr = ...;
>
> string myCString = cast(string)ptr[0 .. strLen];
>
> I can't remember if it will include the null terminator or not, but if
> it does just decrease strLen by 1.

Casting to string is almost always wrong. Casting anything to immutable is
almost always wrong. If you want to use C strings in D without allocating,
they're going to have to be const(char)[], not immutable(char)[], which is
what string is. Otherwise, you risk violating the type system.

Slicing explicitly like this can work just fine, and it will result in
either char[] or const(char)[] depending on whether the pointer is char* or
const char*, but the cast should _not_ be done.

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.

Regardless, do _not_ cast something to immutable if it's not already
immutable. It's just begging for trouble.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list