Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D2, How to convert immutable(char)* to string? [duplicate]

I have a standard char pointer which im trying to cast to a string.

// string to char*
char *x = cast(char*)("Hello World\0");

// char* to string?
string x = cast(string)x;
string x = cast(immutable(char)[])x;

Error!

Any ideas how to cast a char* to a string in D?

like image 740
Gary Willoughby Avatar asked Sep 12 '26 13:09

Gary Willoughby


2 Answers

Use std.conv.to to convert from char* to string. Use std.string.toStringZ to go the other way.

import std.string;
import std.stdio;
import std.conv;

void main()
{
    immutable(char)* x = "Hello World".toStringz();
    auto s = to!string(x);
    writeln(s);
}
like image 175
eco Avatar answered Sep 15 '26 02:09

eco


If you know the exact length you can do this:

immutable(char)* cptr = obj.SomeSource();
int len = obj.SomeLength();

string str = cptr[0..len];

For some cases (like if the string contains \0) that is needed.

like image 45
BCS Avatar answered Sep 15 '26 03:09

BCS