toStringz

@trusted pure nothrow
immutable(char)*
toStringz
(
scope const(char)[] s
)
out (result) { import core.stdc.string : strlen, memcmp; if (result) { auto slen = s.length; while (slen > 0 && s[slen - 1] == 0) --slen; assert (strlen(result) == slen, "The result c string is shorter than the in input string"); assert (result[0 .. slen] == s[0 .. slen], "The input and result string are not equal"); } }

Parameters

s const(char)[]

A D-style string.

Return Value

Type: immutable(char)*

A C-style null-terminated string equivalent to s. s must not contain embedded '\0''s as any C function will treat the first '\0' that it sees as the end of the string. If s.empty is true, then a string containing only '\0' is returned.

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 become invalid during a garbage collection cycle and cause a nasty bug when the C code tries to use it.

Examples

import core.stdc.string : strlen;
import std.conv : to;

auto p = toStringz("foo");
assert(strlen(p) == 3);
const(char)[] foo = "abbzxyzzy";
p = toStringz(foo[3 .. 5]);
assert(strlen(p) == 2);

string test = "";
p = toStringz(test);
assert(*p == 0);

test = "\0";
p = toStringz(test);
assert(*p == 0);

test = "foo\0";
p = toStringz(test);
assert(p[0] == 'f' && p[1] == 'o' && p[2] == 'o' && p[3] == 0);

const string test2 = "";
p = toStringz(test2);
assert(*p == 0);

assert(toStringz([]) is toStringz(""));

Meta