wiki:Documentation/Serialization

Version 1 (modified by Christoph Mayer, 15 years ago) ( diff )

--

Serialization Tutorial

First Steps

In this section we introduce a simple example to show how the serialization works in practice. Two examples are given: First, we show how the inline serialization for small and bit-sensitive works. Second, we show how serialization works with virtual classes.

Inline serialization

Non-virtual inline serialization is reasonable on small or bit-sensitive objects (for example IP-Adresses, Ports etc.). To add serialization to an object it must be inherited from the Serializable class and a specification of the SERIALIZEABLE macro:

#include<serialization.h>

USING_SERIALIZATION; /* use serialization namespaces */

class IPv4Address : public Serializeable { SERIALIZEABLE
private:
    uint8_t a,b,c,d;
public:
    IPv4Address() {
        a=1;b=2;c=3;d=4;
    }
};

In the next step, a serializer can be added to this class:

SERIALIZER_BEGIN( IPv4Address, DEFAULT_V, X )
   X && a && b && c && d;
SERIALIZER_END()

for convenience or personal taste, the macros can also be replaced with

sznBeginDefault( IPv4Address, X )
   X && a && b && c && d;
sznEnd()

In this case we assume that an IP-Address can be mapped bijectively -- therefore no special treatment of serialization and deserialization is needed. So, what happens here is, that a inline serializer is created for class IPv4Address. DEFAULT_V specifies that this serializer is used as default variant and X specifies the variable of the stream that is used to serialize the object. To serialize this object one can use the data_serialize methods:

IPv4Address addr;
Data data = data_serialize( addr );
cout << data << endl;

which outputs

Binary=[01020304]

As you can see the serialization works quite straits forward. The serialized object can now again deserialized with

IPv4Address addr2;
data_deserialize( addr2, data );

Be aware that this kind of serialization results in highly-optimized and inlined code. To generate serializers that are not-inlined and generated once per class, in the next section we discuss virtual serialization.

Virtual serialization

Differentiation between serialization and deserialization

Serialization of bits and special types

Message specification, serialization and deserialization

Note: See TracWiki for help on using the wiki.