Code snippets‎ > ‎C++‎ > ‎Boost‎ > ‎

Serialization

#include <iostream>
#include <fstream>
 
#include <boost/serialization/export.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
 
class MessageA;
 
class BaseMessage
{
public:
    BaseMessage(int type=0) : type(type) {}
 
    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        ar & type;
    }
 
    virtual void print_type()
    {
        std::cout << "BaseMessage" << std::endl;
    }
    int type;
};
 
class MessageA : public BaseMessage
{
    friend class boost::serialization::access;
public:
    MessageA(int type=0) : BaseMessage(0), m_text("Hello world") {}
 
    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        boost::serialization::void_cast_register(
                static_cast<MessageA *>(NULL),
                static_cast<BaseMessage *>(NULL)            
        );
 
        ar & boost::serialization::base_object<BaseMessage>(*this);
        ar & m_text;
    }
 
    virtual void print_type()
    { 
        std::cout << "MessageA" << std::endl;
    }
 
    std::string m_text;
};
 
BOOST_CLASS_EXPORT(MessageA);
 
void serialize_text(BaseMessage *msg)
{
 
    {   // Write
        std::ofstream ofs("filename");
 
        boost::archive::text_oarchive oa(ofs);
        // write class instance to archive
        oa << msg;
        // archive and stream closed when destructors are called
    }
 
    {   // Read
        BaseMessage *base_msg;
 
        std::ifstream ifs("filename");
        boost::archive::text_iarchive ia(ifs);
        ia >> base_msg;
 
        base_msg->print_type();
    }
}
 
void serialize_binary(BaseMessage *msg)
{
    {   // Write
        std::ofstream ofs("filename.bin");
        boost::archive::binary_oarchive oa(ofs);
 
        oa << msg;
    }
 
    {   // Read
        BaseMessage *base_msg;
 
        std::ifstream ifs("filename.bin");
        boost::archive::binary_iarchive ia(ifs);
        ia >> base_msg;
 
        // Call write() function to show the type
        base_msg->print_type();
    }
}
 
int main()
{
    BaseMessage *msg;
 
    msg = new BaseMessage();
    serialize_text(msg);
    serialize_binary(msg);
 
    msg = new MessageA();
    serialize_text(msg);
    serialize_binary(msg);
};

cmake_minimum_required (VERSION 2.6)

project (Boost_serialize)

# Find boost
set(Boost_USE_STATIC_LIBS   ON)
set(Boost_USE_MULTITHREADED ON)
FIND_PACKAGE(Boost COMPONENTS serialization REQUIRED)
if (Boost_FOUND)
  include_directories(${Boost_INCLUDE_DIRS})
endif (Boost_FOUND)

add_executable(serialize serialize.cpp)
target_link_libraries(serialize ${Boost_LIBRARIES})

Comments