Convert temporary character array to string in D

I am learning D language (I know C ++ well) ... I want to do some Windows-specific things, so I wrote this to try the API:

import core.sys.windows.windows; import std.stdio; string name() { char buffer[100]; uint size = 100; GetComputerNameA(&buffer[0], &size); return buffer; } void main() { writeln(name()); } 

I get in my return expression:

 test.d(11): Error: cannot implicitly convert expression (buffer) of type char[100] to string 

Well, in C ++, it will call the constructor to create the string. It implies implicitly, so it allows you to cast it using the C style: return (string)buffer; .

 test.d(11): Error: C style cast illegal, use cast(string)buffer 

Well, well, I remember a different syntax.

 return cast(string)buffer; 

Now it compiles, but I just get garbage.

I assume this is because it stores the pointer in a string in a temporary buffer. I do not want to do this, I want to copy the characters into a string, but it is annoying that I can not find how to do this?

So the questions are:

  • How to create an actual string from a char array that allocates memory correctly? (Copies characters)

  • Allocating a random size buffer like this and converting to a string seems ugly. Is there a proper way to do this in D? (I'm talking about a general question, and not specifically about this API, just in case there is another API for getting the computer name).

  • If any of these answers in the manual, where should I look for details?

Thanks for any help and advice.

+7
d
source share
2 answers

I think you need:

 string name() { char buffer[100]; uint size = 100; GetComputerNameA(buffer.ptr, &size); return buffer[0 .. size].idup; } 
+7
source share

buffer.idup is the standard way to get an immutable copy. For this case, since you need a dynamic-sized string (and recall that string is actually just shorthand for immutable(char)[] ), you want buffer[0..size].idup using arrays of D arrays.

See http://dlang.org/arrays.html for more details.

(This is a bit nitpick, but you can use buffer.ptr instead of &buffer[0] , mainly for readability.)

+5
source share

All Articles