Printing a C "string" with write(f)ln

Daniel Kozak via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Feb 9 09:04:58 PST 2016


On Tuesday, 9 February 2016 at 16:58:03 UTC, Daniel Kozak wrote:
> On Tuesday, 9 February 2016 at 16:52:09 UTC, Gary Willoughby 
> wrote:
>> On Tuesday, 9 February 2016 at 12:50:27 UTC, Jakob Ovrum wrote:
>>> writefln et al sensibly does *not* assume that a pointer to 
>>> char is a C string, for memory safety purposes.
>>>
>>> Print the result of std.string.fromStringz[1] instead:
>>>
>>> writeln(fromStringz(pString));
>>> writefln("%s", fromStringz(pString));
>>>
>>> [1] http://dlang.org/phobos/std_string#fromStringz
>>
>> Or use `to` like this:
>>
>> import std.conv;
>> writefln("%s", pString.to!(string));
>
> this will allocate new string which can be performance problem.
> Maybe:
>
> writefln("%s", pString.to!(char[]));
>
> But I do not know if this works and does not allocate

void main() {
     char[] chars = cast(char[])"Ahoj svete";

     char* cstr = chars.ptr;
     auto s1 = to!string(cstr);
     auto s2 = to!(char[])(cstr);
     auto s3 = fromStringz(cstr);

     writeln(cstr);   //46D310
     writeln(s1.ptr); //7F0062EF1000
     writeln(s2.ptr); //7F0062EF1010
     writeln(s3.ptr); //46D310
}


More information about the Digitalmars-d-learn mailing list