toStringz

  1. immutable(char)* toStringz(const(char)[] s)
    @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"); } }
  2. immutable(char)* toStringz(string s)

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

1 import core.stdc.string : strlen;
2 import std.conv : to;
3 
4 auto p = toStringz("foo");
5 assert(strlen(p) == 3);
6 const(char)[] foo = "abbzxyzzy";
7 p = toStringz(foo[3 .. 5]);
8 assert(strlen(p) == 2);
9 
10 string test = "";
11 p = toStringz(test);
12 assert(*p == 0);
13 
14 test = "\0";
15 p = toStringz(test);
16 assert(*p == 0);
17 
18 test = "foo\0";
19 p = toStringz(test);
20 assert(p[0] == 'f' && p[1] == 'o' && p[2] == 'o' && p[3] == 0);
21 
22 const string test2 = "";
23 p = toStringz(test2);
24 assert(*p == 0);

Meta

Suggestion Box / Bug Report