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.
d
jcoder
source share