IOLink 1.11.0
Loading...
Searching...
No Matches
serializationArray.cpp

This code demonstrates how to serialize and deserialize an ArrayXf object to/from a file.

This code demonstrates how to serialize and deserialize an ArrayXf object to/from a file.The code creates a 2D array of size 4x2, fills it with float values and writes it to a file. It then reads the data back and prints the content of the array.

#include <iostream>
#include <boost/filesystem.hpp>
#include <iolink/serialization/Serialization.h>
#include <iolink/storage/StreamAccessFactory.h>
using namespace iolink;
static void
serializeArrayXf()
{
// path to a temporary file in the temp directory
const boost::filesystem::path tmpFilePath = boost::filesystem::temp_directory_path() / "serialization_array_cpp.txt";
VectorXu64 shape{4, 2};
ArrayXf arrayf(shape);
// fill the array with some values, cell by cell
arrayf.setAt(VectorXu64{0, 0}, 0.0F);
arrayf.setAt(VectorXu64{1, 0}, 1.0F);
arrayf.setAt(VectorXu64{2, 0}, 2.0F);
arrayf.setAt(VectorXu64{3, 0}, 3.0F);
arrayf.setAt(VectorXu64{0, 1}, 10.0F);
arrayf.setAt(VectorXu64{1, 1}, 11.0F);
arrayf.setAt(VectorXu64{2, 1}, 12.0F);
arrayf.setAt(VectorXu64{3, 1}, 13.0F);
std::cout << "Serialize array into " << tmpFilePath << std::endl;
// open a streamAccess to serialize the array to a file
std::shared_ptr<StreamAccess> dst = StreamAccessFactory::openFileWrite(tmpFilePath.string());
if (!dst)
{
std::cerr << "Impossible to open file " << tmpFilePath.string() << std::endl;
}
// array is serialized to the file
Serialization::encodeArrayXf(arrayf, dst);
// flush and close the streamAccess
dst.reset();
// open another streamAccess to read the serialized array from the file
std::shared_ptr<StreamAccess> src = StreamAccessFactory::openFileRead(tmpFilePath.string());
if (!src)
{
std::cerr << "Impossible to open file " << tmpFilePath.string() << std::endl;
}
// array is deserialized from the file
ArrayXf arrayRead = Serialization::decodeArrayXf(src);
// print the content of the array
std::cout << "Content of unserialized array:" << arrayRead.toString() << std::endl;
}
int
main(int argc, char** argv)
{
serializeArrayXf();
return EXIT_SUCCESS;
}