Binary serialization of a struct

Nordlöw per.nordlow at gmail.com
Tue Sep 19 06:32:52 UTC 2017


On Saturday, 16 September 2017 at 03:30:51 UTC, Joseph wrote:
> Are there any simple direct serialization libraries where I can 
> mark elements of a class or struct that I want serialized with 
> an attribute and it will take care of all the rest(including 
> recursive structures, arrays, etc) then deserialize back in to 
> the structs?
>
> I want something straight forward without allot of plumbing on 
> my end.

https://github.com/msgpack/msgpack-d

is about as simple as it can get:

import std.file;
import msgpack;

struct S { int x; float y; string z; }

void main()
{
     S input = S(10, 25.5, "message");

     // serialize data
     ubyte[] inData = pack(input);

     // write data to a file
     write("file.dat", inData);

     // read data from a file
     ubyte[] outData = cast(ubyte[])read("file.dat");

     // unserialize the data
     S target = outData.unpack!S();

     // verify data is the same
     assert(target.x == input.x);
     assert(target.y == input.y);
     assert(target.z == input.z);
}


More information about the Digitalmars-d-learn mailing list