Download Reference Manual
The Developer's Library for D
About Wiki Forums Source Search Contact

serialize a struct

Moderators: larsivi kris

Posted: 07/26/07 16:40:07

I was reading through the docs to find out how to serialize a struct:

struct Wombat {

void read (IReader input) {...} void write (IWriter output) {...}

}

Wombat wombat;

output (&wombat.write); input (&wombat.read);

I came accross this... but I'm still not sure what i should write in the functions read/write (I'm new to D too)

Cheers for any help ;)

Raedwulf

Author Message

Posted: 07/27/07 11:42:43

The read() and write() methods should direct the serialization of select content within the aggregate. In particular, read() should ensure the aggregate is in a usable state where there are some fields that are not persisted. Classes are generally simpler to apply, because they support interface usage:

class Foo
{
  int x;
  char[] y;

  void read(Reader input)
  {
     input (x) (y);
  }

  void write(Writer output)
  {
     output (x) (y);
  }
}

Reader read;
Writer write;

auto foo = new Foo;
write (foo);
read (foo);

Structs operate in a similar manner, but usage requires a bit more assistance to get the ball rolling (lack of interfaces):

struct Foo
{
  int x;
  char[] y;

  void read(Reader input)
  {
     input (x) (y);
  }

  void write(Writer output)
  {
     output (x) (y);
  }
}

Reader read;
Writer write;

auto foo = new Foo;
write (&foo.write);
read (&foo.read);

Posted: 07/27/07 12:35:43

Thank you! :) I think this is what I need :D.

Raedwulf