更新:在我四处搜索并阅读代码中的 doxygen 注释后,我设法让它工作。问题是我在使用resize()
方法之前错过了演员阵容,也没有std::ios::binary
用于流。如果您想做类似的事情,最好检查 Azoth 的答案。
我正在尝试Eigen::Matrix
使用 Cereal 序列化类型。这就是我所拥有的(大致基于https://gist.github.com/mtao/5798888和中的类型cereal/types
):
#include <cereal/cereal.hpp>
#include <cereal/archives/binary.hpp>
#include <Eigen/Dense>
#include <fstream>
namespace cereal
{
template <class Archive, class _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols> inline
typename std::enable_if<traits::is_output_serializable<BinaryData<_Scalar>, Archive>::value, void>::type
save(Archive & ar, Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols> const & m)
{
int rows = m.rows();
int cols = m.cols();
ar(make_size_tag(static_cast<size_type>(rows * cols)));
ar(rows);
ar(cols);
ar(binary_data(m.data(), rows * cols * sizeof(_Scalar)));
}
template <class Archive, class _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols> inline
typename std::enable_if<traits::is_input_serializable<BinaryData<_Scalar>, Archive>::value, void>::type
load(Archive & ar, Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols> const & m)
{
size_type size;
ar(make_size_tag(size));
int rows;
int cols;
ar(rows);
ar(cols);
const_cast<Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols> &>(m).resize(rows, cols);
ar(binary_data(const_cast<_Scalar *>(m.data()), static_cast<std::size_t>(size * sizeof(_Scalar))));
}
}
int main() {
Eigen::MatrixXd test = Eigen::MatrixXd::Random(10, 3);
std::ofstream out = std::ofstream("eigen.cereal", std::ios::binary);
cereal::BinaryOutputArchive archive_o(out);
archive_o(test);
std::cout << "test:" << std::endl << test << std::endl;
out.close();
Eigen::MatrixXd test_loaded;
std::ifstream in = std::ifstream("eigen.cereal", std::ios::binary);
cereal::BinaryInputArchive archive_i(in);
archive_i(test_loaded);
std::cout << "test loaded:" << std::endl << test_loaded << std::endl;
}