Skip to content
Marc edited this page Jun 29, 2016 · 17 revisions

Fields are the simplest serialized data object. It has a name, and stores a single data type. The valid data types are: bool, char, byte, short, int, long long, float, double, std::string
They are a good choice if you only need to store the contents of a single variable.

Using fields

To use fields, you only need to include Cereal.h.
Now, type the following in your code:

Cereal::Field* myField = new Cereal::Field("Field name", 'A');

That will create a field with the name "Field name" and will store the character A. Now, you can use the function Field::write(Buffer& buffer) to serialize its contents to a buffer:

myField->write(buffer); // Write the contents of a field to the buffer

Instead, if you need to deserialize the contents of a field, you will have to read a buffer containing a field, and then call Field::getValue<dataType>():

Cereal::Field* myField = new Cereal::Field; // We create an empty field because we will overwrite it anyway
myField->read(buffer); // Now the field is full of data
char deserializedData = myField->getValue<char>(); // We store the contents of the field

For more information on how to use fields with objects, check out the objects page.

Sample code

#include <Cereal.h> // Include the library

int main()
{
    Cereal::Buffer buffer(1024); // Create a buffer with 1024 bytes
    Cereal::Field* myField = new Cereal::Field("Field name", 'A');

    // Writing a field
    myField->write(buffer); // Write the field to the buffer

    // Reading a field
    Cereal::Field* otherField = new Cereal::Field; // Create another field
    buffer.setOffset(0); // Move the buffer back to the begining
    otherField->read(buffer); // Read the field from the buffer
    char data = otherField->getValue<char>(); // Now data should be equal to 'A'

    // Adding a field to an object
    Cereal::Object* obj = new Cereal::Object("Object name");
    obj->add(myField);

    // Getting a field from an object
    Cereal::Field* field = obj->getField("Field name");

    // Free dynamic memory
    delete obj;
    delete myField;
    delete otherField;

    return 0;
}