Serializing Eigen::Matrix using Cereal library

后端 未结 2 1933
予麋鹿
予麋鹿 2021-01-02 23:14

UPDATED: I managed to get it to work after I googled around and read the doxygen comments in code. Problem was that I missed the cast before using res

2条回答
  •  借酒劲吻你
    2021-01-02 23:58

    Based on @Azoth answer (whom I would like to give the whole credit, anyway), I improved the template a bit to

    • work also for Eigen::Array (rather than just Eigen::Matrix);
    • not serialize compile-time dimensions (that makes quite some storage difference for e.g. Eigen::Vector3f).

    This is the result:

    namespace cereal
    {
      template  inline
        typename std::enable_if, Archive>::value, void>::type
        save(Archive & ar, Eigen::PlainObjectBase const & m){
          typedef Eigen::PlainObjectBase ArrT;
          if(ArrT::RowsAtCompileTime==Eigen::Dynamic) ar(m.rows());
          if(ArrT::ColsAtCompileTime==Eigen::Dynamic) ar(m.cols());
          ar(binary_data(m.data(),m.size()*sizeof(typename Derived::Scalar)));
        }
    
      template  inline
        typename std::enable_if, Archive>::value, void>::type
        load(Archive & ar, Eigen::PlainObjectBase & m){
          typedef Eigen::PlainObjectBase ArrT;
          Eigen::Index rows=ArrT::RowsAtCompileTime, cols=ArrT::ColsAtCompileTime;
          if(rows==Eigen::Dynamic) ar(rows);
          if(cols==Eigen::Dynamic) ar(cols);
          m.resize(rows,cols);
          ar(binary_data(m.data(),static_cast(rows*cols*sizeof(typename Derived::Scalar))));
        }
    }
    

提交回复
热议问题