Write struct to file

Timon Gehr timon.gehr at gmx.ch
Sat Feb 25 10:15:23 PST 2012


On 02/25/2012 07:03 PM, Chopin wrote:
> Hello!
>
> import std.stdio;
>
> struct nagger
> {
> string name;
> int age;
> double weight;
> string msg;
> }
>
> void main()
> {
> auto lal = new nagger();
> lal.name = "AHAHAHAHHA";
> lal.age = 23;
> lal.weight = 108.5;
> lal.msg = "fgfdgfdgfdgfdgfdgfdg";
> writeln(cast(ubyte[])(lal));
> }
>
> Gives error: Error: e2ir: cannot cast lal of type nagger* to type ubyte[]
> I have bad knowledge about this and don't understand why I cant do this :(
> What I really want is an array of naggers and save them binary to a file :)
> This was like my step 1, and it failed miserably...
>
> Thanks for help.
>

Structs are not castable to arrays directly. You can achieve what you 
want like this (untested, but should work).

(cast(void*)&lal)[0..nagger.sizeof];



More information about the Digitalmars-d-learn mailing list