Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use boost serialization for binary output?

Tags:

c++

boost

what is difference between functions boost::serialization::binary_object(void * t, size_t size) and boost::serialization::make_binary_object(void * t, size_t size)?

How can i use them for getting actual output binary file ?

like image 644
Pratik Patil Avatar asked Jul 13 '26 12:07

Pratik Patil


2 Answers

Welcome to SO!!

Here is an example showing how to use it.

#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/serialization/binary_object.hpp>
#include <boost/serialization/serialization.hpp>
#include <iostream>
#include <sstream>

using boost::serialization::make_binary_object;

enum class Example : uint8_t {
    A = 1,
    B = 2,
};

int main() {

    std::stringstream stream;
    boost::archive::binary_oarchive ar(stream, boost::archive::no_header);

    auto data = Example::A;
    ar << make_binary_object(&data, sizeof(data));

    std::cout << "Size: " << stream.str().size() << "\n";
}

If you want to save the binary object in a file, here is an example that will save it in a file called data.dat

#include <fstream>

using boost::serialization::make_binary_object;

enum class Example : uint8_t {
    A = 1,
    B = 2,
};

int main() {

    std::ofstream f("data.dat", std::ofstream::binary);
    boost::archive::binary_oarchive ar(f, boost::archive::no_header);

    auto data = Example::A;
    ar << make_binary_object(&data, sizeof(data));  
}

After running the code the file looks something like this
data.dat file

From the boost source code comments posted by @StoryTeller
make_binary_object() is just a little helper to support the convention that all serialization wrappers follow the naming convention make_xxxxx

like image 131
Damian Avatar answered Jul 16 '26 06:07

Damian


boost::serialization::make_binary_object(void * t, size_t size) is a helper and calls boost::serialization::binary_object(void * t, size_t size). The helper is provided to preserve naming convention make_xxxxx

To save the object to a binary file you need to create an Archive and call void save(Archive & ar, const unsigned int /* file_version */) method of your binary_object

like image 39
Oleg Avatar answered Jul 16 '26 07:07

Oleg