Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::serialization in C++, deserialization in Python

Tags:

c++

python

boost

I produce some data in C++ that I want to access in a Python program. I have figured out how to serialize/deserialize to/from a binary file with boost in C++, but not how to access the data in Python (without manually parsing the binary file).

Here is my C++ code for serialization:

/* Save some data to binary file */
template <typename T>
int serializeToBinaryFile( const char* filename, const T& someValue,
                           const vector<T>& someVector )
{
    ofstream file( filename, ios::out | ios::binary | ios::trunc );

    if ( file.is_open() )
    {
        boost::archive::text_oarchive oa(file);

        int sizeOfDataType = sizeof(T);

        oa & sizeOfDataType;
        oa & someValue;
        oa & someVector;

        file.close();

        return 0;
    } else {
        return 1;
    }
}

Here is my C++ code for deserialization:

/* Load some data from binary file */
template <typename T>
int deSerializeFromBinaryFile( const char* filename, int& sizeOfDataType,
                               T& someValue, vector<T>& someVector )
{
    ifstream file( filename, ios::in | ios::binary );

    if ( file.is_open() )
    {
        boost::archive::text_iarchive ia(file);

        ia & sizeOfDataType;
        ia & someValue;
        ia & someVector;

        file.close();

        return 0;
    } else {
        return 1;
    }
}

How can I load the value and vector to objects in a Python program?

like image 888
fromGiants Avatar asked May 29 '15 07:05

fromGiants


2 Answers

The boost documentation makes reference to the fact that the binary representation is not portable, or even guaranteed to be consistent across different versions of your program.

You may want to use the xml serializer that's available in boost::serialization and then use an xml parser in python to read.

Instructions (and an example) on how to do this are here: http://www.boost.org/doc/libs/1_58_0/libs/serialization/doc/tutorial.html#archives

Note the use of the NVP macro to name the items in the archive.

like image 63
Richard Hodges Avatar answered Oct 09 '22 20:10

Richard Hodges


Use boost python to expose your deserialization function to python. You will need to expose the function for each type you need separately (can't expose templates to python).

like image 39
doqtor Avatar answered Oct 09 '22 21:10

doqtor