Converting a temporary character array to a string in D

吃可爱长大的小学妹 提交于 2020-01-03 08:52:36

问题


I'm learning D language (I know C++ well)... I want to do some Windows specific stuff so I wrote this just to try out 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 statement:

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

Ok, in C++ it would call the constructor to make a string. It says implicit so lets cast it with a C style cast: return (string)buffer;.

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

Ah ok, I remember, different syntax.

return cast(string)buffer;

Now it compiles but I just get garbage.

I assume that is is because it's storing a pointer in the string to the temporary buffer. I don't want to do this, I want to copy the characters into a string but annoyingly I can't seem to find how to do this?

So questions:

  1. How do I construct an actual string from a char array that allocates storage properly? (Copies the characters)

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

  3. If either of those are answered in a manual where should I have looked to find details?

Thanks for any help and advice.


回答1:


I think you need:

string name()
{
   char buffer[100];
   uint size = 100;

   GetComputerNameA(buffer.ptr, &size);

   return buffer[0 .. size].idup;
}



回答2:


buffer.idup is the standard way to get an immutable copy. For this case, since you want a dynamically-sized string (and recall that string is really just shorthand for immutable(char)[]), you want buffer[0..size].idup, using D's array slicing.

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

(This is a bit of a nitpick, but you may want to use buffer.ptr instead of &buffer[0], mostly for readability's sake.)



来源:https://stackoverflow.com/questions/32220621/converting-a-temporary-character-array-to-a-string-in-d

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!