简体   繁体   中英

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 ?

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文件

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM