Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a temporary character array to a string in D

Tags:

d

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.

like image 517
jcoder Avatar asked Aug 26 '15 07:08

jcoder


People also ask

How do I turn a char array into a string?

The method valueOf() will convert the entire array into a string. String str = String. valueOf(arr);

What is Chararray?

A character array is a sequence of characters, just as a numeric array is a sequence of numbers. A typical use is to store a short piece of text as a row of characters in a character vector.


2 Answers

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

like image 157
Fusxfaranto Avatar answered Sep 29 '22 14:09

Fusxfaranto


I think you need:

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

   GetComputerNameA(buffer.ptr, &size);

   return buffer[0 .. size].idup;
}
like image 25
sibnick Avatar answered Sep 29 '22 13:09

sibnick