Pratik Patil
Pratik Patil

Reputation: 101

How to use boost serialization for binary output?

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 ?

Upvotes: 3

Views: 4113

Answers (2)

Damian
Damian

Reputation: 4631

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

Upvotes: 5

Oleg
Oleg

Reputation: 766

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

Upvotes: 2

Related Questions