Skip to content
Marc edited this page Aug 14, 2018 · 8 revisions

Arrays are used to store C++ arrays. The supported data types are: bool, char, byte, short, int, long long, float, double and std::string.
Arrays are really useful to store coordinates, vectors, vertices...

Using arrays

Arrays are located inside src/Array.h, but we strongly recommend you to include the library header file Cereal.h instead.

To create an array, we just have to give it a name and an array, along with the item count:

int myArrayData[] = { 1, 2, 3, 4 }; // Data to be stored by the array
Cereal::Array* myArray = new Cereal::Array("Array name", myArrayData, 4); // Create an array with the data 'myArrayData'

That will create an array with the name Array name and will contain { 1, 2, 3, 4 }.
Next, we can write everything into a buffer:

myArray->write(buffer) // Write 'myArray' to the buffer 'buffer'

Array::write() will return true if the array was successfully serialized, and false otherwise. Normally, if the function fails is because the buffer is too small to store that array.

To read an array, we just have to call Array::read(Buffer& buffer):

Cereal::Array otherArray = new Cereal::Array; // Create an empty array
otherArray->read(buffer); // Read the array data from the buffer

And now our array should contain the data. To retrieve the original array we can use two functions: the first one is template<typename T> std::vector<T>& Array::getArray(), which returns a vector with the original array. The other function is template<typename T> T* getRawArray(T* mem). That last one copies the array data to a memory address we give to it, so it's better if we want to have a pure C/C++ array. Anyway, here's how to use both:

std::vector<int> arrayData = otherArray->getArray<int>(); // Get the vector with the array data
// ...
int* arrayData = new int[otherArray->getCount()]; // Create a pointer to store our data
arrayData = otherArray->getRawArray<int>(arrayData); // Store the array data in 'arrayData'

For more information about how to use arrays with objects, check out objects

Sample code

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

int main()
{
    Cereal::Buffer buffer(1024); // Create a buffer with 1024 bytes
    int TheNumbers[] = { 4, 8, 15, 16, 23, 42 }
    Cereal::Array* myArray = new Cereal::Array("Array name", TheNumbers, 6);

    // Writing an array
    myArray->write(buffer); // Write the array to the buffer

    // Reading an array
    Cereal::Array* otherArray = new Cereal::Array; // Create another array
    buffer.setOffset(0); // Move the buffer back to the beginning
    otherArray->read(buffer); // Read the array from the buffer
    std::vector<int> data = otherArray->getArray<int>(); // Now data should contain 4, 8, 15, 16, 23, 42

    // Free dynamic memory
    delete myArray;
    delete otherArray;

    return 0;
}