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

Objects are the main component of databases. An object can store up to 65536 fields and 65536 arrays.

Using objects

Objects can be found inside src/Object.h. However, you should include Cereal.h, as it also includes all the other files from the library.

Lets begin creating an object:

Cereal::Object* myObject = new Cereal::Object("Object name");

Now, our object has the name "Object name" and is ready to store fields and arrays:

short arrayValues[] = { 32, 18, 21, 30 };

Cereal::Array* myArray = new Cereal::Array("Array name", arrayValues, 4); // We create an array with 4 values
Cereal::Field* myField = new Cereal::Field("Field name", 3.141592f); // We store pi inside that field

myObject->add(myArray); // Add the array to the object
myObject->add(myField); // Add the field to the object

Once our object has all the fields and all the arrays we need inside it, we can call Object::write(Buffer& buffer) to serialize it:

Cereal::Buffer buffer(1024); // We create a buffer of 1 kilobyte
myObject->write(buffer);

Finally, we can deserialize our object and get its fields and arrays like so:

Cereal::Object* obj = new Cereal::Object; // We create an empty object
obj->read(buffer); // Read the buffer and get all the fields and arrays

Cereal::Field* field = obj->getField("Field name"); // Get the field
Cereal::Array* array = obj->getArray("Array name"); // Get the array

If the field or the array is not found, it will return nullptr.

Sample code

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

int main()
{
    Cereal::Buffer buffer(1024); // Create a buffer

    int arrayData[] = { 10, 20, 30, 40 }; // Create an array

    Cereal::Object* myObject("Test object"); // Create an object

    // Adding fields and arrays to objects
    myObject->add(new Cereal::Field("Test field", 42)); // Create a field and add it to the object
    myObject->add(new Cereal::Array("Test array", arrayData, 4)); // Create an array and add it to the object

    // Writing objects
    myObject->write(buffer);

    // Reading objects
    Cereal::Object* otherObject = new Cereal::Object; // Create another object
    buffer.setOffset(0); // Move the offset of the buffer to the beginning
    otherObject->read(buffer); // Read the buffer

    // Getting a field and an array from an object
    Cereal::Field* field = otherField->getField("Test field"); // Get the field
    Cereal::Array* array = otherField->getArray("Test array"); // Get the array

    // Free dynamic memory
    delete myObject; // Objects will automatically delete all the fields and arrays they contain
    delete otherObject;

    return 0;
}