5

I'm trying to serialize Eigen's matrix. So that I can serialize a more complex object. I'm using Matrix as a base class and include the serialization in the derived class. I'm confused on how to address Matrix.data(), which returns a c-style array (if i'm correct). This is my attempt:

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>

template < class TEigenMatrix>
class VariableType : public TEigenMatrix {
private:
  friend class boost::serialization::access;
  template<class Archive>
  void serialize(Archive & ar, const unsigned int version)
  {
      ar & this.data();
  }
public:
};

I would like to use it as a "wrapper" :

VariableType<Matrix<double,3,1>> serializableVector;

in place of

Matrix<double,3,1> vector;
kirill_igum
  • 3,953
  • 5
  • 47
  • 73

2 Answers2

9

Since Matrix in Eigen are dense, so you can replace the for-loop in Jakob's answer with make_array as:

ar & boost::serialization::make_array(t.data(), t.size());

I made a more detailed answer in this post: https://stackoverflow.com/a/23407209/1686769

Community
  • 1
  • 1
iNFINITEi
  • 1,504
  • 16
  • 23
8

By placing the following free function into your compilation unit, you effectively make Boost.Serialization aware of how to serialize Eigen types:

namespace boost
{
    template<class Archive, typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols>
    inline void serialize(
        Archive & ar, 
        Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols> & t, 
        const unsigned int file_version
    ) 
    {
        for(size_t i=0; i<t.size(); i++)
            ar & t.data()[i];
    }
}

In the example you gave, you should then be able to do (untested):

void serialize(Archive & ar, const unsigned int version)
{
    ar & *this;
}

Have a look at my previous answer on serialization of Eigen types using Boost.Serialization for a more detailed example.

Community
  • 1
  • 1
Jakob
  • 2,360
  • 15
  • 21
  • 1
    Wouldn't it make sense to write the serialization for `Eigen::DenseBase`? I think in this way one could also serialize `Eigen::Array` with the same code, see: http://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html – Robert Rüger Feb 19 '13 at 12:59