char[] <--> void*

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Mon Feb 26 09:57:54 PST 2007


e-t172 wrote:
> Hi,
> 
> (I'm french, sorry for my bad english)
> 
> The following doesn't compile :
> 
> import std.stdio;
> 
> void bar(void* str)
> {
>     writefln(cast(char[]) str);
> }
> 
> void main()
> {
>     char[] foo;
> 
>     foo = "Hello world";
> 
>     bar(cast(void*) foo);
> }
> 
> $ dmd void.d
> void.d(5): Error: e2ir: cannot cast from void* to char[]
> 
> How should I write it to make it work ?

<obvious>
Remove the casts and change the argument type of bar to char[]:
---
import std.stdio;

void bar(char[] str)
{
     writefln(str);
}

void main()
{
     char[] foo;

     foo = "Hello world";

     bar(foo);
}
---
</obvious>


Alternatives:

Arrays need a length, which you could also pass separately:
---
import std.stdio;

void bar(size_t length, void* str)
{
     writefln((cast(char*) str)[0 .. length]);
}

void main()
{
     char[] foo;

     foo = "Hello world";

     bar(foo.length, cast(void*) foo);
}
---


If you insist on passing a C-style string in a void* :
---
import std.stdio;
import std.string;

void bar(void* str)
{
     // Convert back to char[] and write to console
     writefln(toString(cast(char*) str));
}

void main()
{
     char[] foo;

     foo = "Hello world";

     // Ensure presence of 0-terminator
     // (This is not necessary for string literals in current DMD
     // versions, but relying on this is a very bad habit. Also, it
     // would break if you ever try to pass a string not directly
     // initialized by a string literal)
     bar(toStringz(foo));
}
---


More information about the Digitalmars-d-learn mailing list