使用boost.serialization序列化Eigen的矩阵

kir*_*gum 5 derived-class boost-serialization eigen

我正在尝试序列化Eigen的矩阵.这样我就可以序列化一个更复杂的对象.我使用Matrix作为基类,并在派生类中包含序列化.我很困惑如何处理Matrix.data(),它返回一个c风格的数组(如果我是正确的).这是我的尝试:

#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:
};
Run Code Online (Sandbox Code Playgroud)

我想用它作为"包装器":

VariableType<Matrix<double,3,1>> serializableVector;
Run Code Online (Sandbox Code Playgroud)

代替

Matrix<double,3,1> vector;
Run Code Online (Sandbox Code Playgroud)

iNF*_*TEi 9

由于Eigen中的Matrix是密集的,所以你可以用make_array替换Jakob答案中的for循环:

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

我在这篇文章中做了更详细的回答:https://stackoverflow.com/a/23407209/1686769


Jak*_*kob 8

通过将以下自由函数放入编译单元,您可以有效地使Boost.Serialization知道如何序列化特征类型:

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];
    }
}
Run Code Online (Sandbox Code Playgroud)

在您给出的示例中,您应该能够(未经测试):

void serialize(Archive & ar, const unsigned int version)
{
    ar & *this;
}
Run Code Online (Sandbox Code Playgroud)

有关更详细的示例,请查看我之前使用Boost.Serialization序列化特征类型的答案.