将零终止字符串转换为D字符串

Nor*_*löw 3 d c-strings null-terminated string-conversion

在Phobos中是否有一个函数用于将零终止字符串转换为D字符串?

到目前为止,我只发现了相反的情况toStringz.

我在下面的代码片段中需要这个

// Lookup user name from user id
passwd pw;
passwd* pw_ret;
immutable size_t bufsize = 16384;
char* buf = cast(char*)core.stdc.stdlib.malloc(bufsize);
getpwuid_r(stat.st_uid, &pw, buf, bufsize, &pw_ret);
if (pw_ret != null) {
    // TODO: The following loop maybe can be replace by some Phobos function?
    size_t n = 0;
    string name;
    while (pw.pw_name[n] != 0) {
        name ~= pw.pw_name[n];
        n++;
    }
    writeln(name);
}
core.stdc.stdlib.free(buf);
Run Code Online (Sandbox Code Playgroud)

我用它来查找用户ID的用户名.

我现在假设UTF-8兼容性.

Ada*_*ppe 6

有两种简单的方法:slice或std.conv.to:

const(char)* foo = c_function();
string s = to!string(foo); // done!
Run Code Online (Sandbox Code Playgroud)

或者,如果您要暂时使用它,或者知道它不会被写入或在其他地方释放,您可以对其进行切片:

immutable(char)* foo = c_functon();
string s = foo[0 .. strlen(foo)]; // make sure foo doesn't get freed while you're still using it
Run Code Online (Sandbox Code Playgroud)

如果你认为它可以被释放,你也可以通过切片然后复制来复制它:foo [0..strlen(foo)].dup;

在所有数组中,切片指针的工作方式相同,而不仅仅是字符串:

int* foo = get_c_array(&c_array_length); // assume this returns the length in a param
int[] foo_a = foo[0 .. c_array_length]; // because you need length to slice
Run Code Online (Sandbox Code Playgroud)