将临时字符数组转换为D中的字符串 [英] Converting a temporary character array to a string in D

查看:80
本文介绍了将临时字符数组转换为D中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习D语言(我非常了解C ++)...我想做一些Windows特定的东西,所以我写这个只是为了尝试API:

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());
}

我收到了我的退货单:

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

好吧,在C ++中,它将调用构造函数来生成字符串。它说是隐式的,所以让我们用C样式强制转换:返回(字符串)缓冲区;

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?

所以问题:


  1. 如何从可正确分配存储空间的char数组构造实际字符串? (复制字符)

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

分配这样的随机大小的缓冲区并将其转换为字符串似乎很丑。在D中有正确的方法吗? (我在谈论的是一般性问题,不是专门针对此API,以防万一还有另一个API可以获取计算机名称。)

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).

如果其中任何一个

谢谢您的帮助和建议。

推荐答案

我认为您需要:

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

   GetComputerNameA(buffer.ptr, &size);

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

这篇关于将临时字符数组转换为D中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆