Saturday 29 August 2009

Using Boost Serialization and errors you may encounter

To update your list of software packages in Ubuntu:
sudo apt-get update

To get the Boost Serialization library:
sudo apt-get install libboost-serialization-dev

I'm using:
libboost-serialization-dev version 1.34.1-4ubuntu3
g++ version 4.2.4-1ubuntu3


In main.cpp:
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/access.hpp>
#include <boost/serialization/base_object.hpp>
#include <fstream>

using namespace
std;

class
Actor
{

public
:
Actor( void ) {}
Actor( char gender )
:
gender( gender )
{}

char
Gender( void ) const { return gender; }
private
:
friend class
boost::serialization::access;
template
<class Archive>
void
serialize(Archive & ar, const unsigned int version)
{

ar & gender;
}

char
gender;
};


void
save( const Actor& actor, string filename )
{

ofstream ofs( filename.c_str() );
boost::archive::text_oarchive oa( ofs );
oa & actor;
}


void
load( Actor& actor, string filename )
{

ifstream ofs( filename.c_str() );
boost::archive::text_iarchive ia( ofs );
ia & actor;
}


void
testBoostSerialization( void )
{

Actor actorAlpha( 'm' );
Actor actorBravo( 'f' );

// save
string filename = "sav.sav";
save( actorAlpha, filename );

// test
assert( actorBravo.Gender() == 'f' );

// load
load( actorBravo, filename );

// test
assert( actorBravo.Gender() == 'm' );
}


int
main( int argc, const char* argv[] )
{

testBoostSerialization();
return
EXIT_SUCCESS;
}


In Makefile (remember to put a real tab before where it says 'g++'):
all:
g++ -g -Wall testBoostSerializationInheritance.cpp -lboost_serialization


Error you may encounter 1:
/usr/include/boost/archive/detail/oserializer.hpp:566: error: invalid application of ‘sizeof’ to incomplete type ‘boost::STATIC_ASSERTION_FAILURE<false>
To fix this error, make sure that you only pass const objects boost::archive::text_oarchive.

Error you may encounter 2:
terminate called after throwing an instance of 'boost::archive::archive_exception'
what(): invalid signature
Aborted

To fix this error, make sure that you have only one of either boost::archive::text_oarchive or boost::archive::text_iarchive created at a time.

No comments:

Post a Comment