使用谷物序列化犰狳基质

时间:2016-10-30 13:21:51

标签: c++ serialization armadillo cereal

我正在尝试使用Cereal库实现armadillo矩阵序列化。 SO有样本here。不幸的是我无法使用Boost。 到目前为止我得到了这个。在mat_extra_meat.hpp里面

template<class Archive, class eT>
typename std::enable_if<cereal::traits::is_output_serializable<cereal::BinaryData<eT>, Archive>::value, void>::type
save( Archive & ar, const Mat<eT>& m ) {
    uword n_rows_local, n_cols_local, n_elem_local, vec_state_local;
    std::size_t data_size;
    n_rows_local = m.n_rows;
    n_cols_local = m.n_cols;
    n_elem_local = m.n_elem;
    vec_state_local = m.vec_state;
    ar( n_rows_local, n_cols_local, n_elem_local, vec_state_local );
    data_size = static_cast< std::size_t >( m.n_elem * sizeof( eT ) );
    ar( cereal::binary_data( reinterpret_cast< void * const >( const_cast< eT* >( m.memptr() ) ), data_size ) );
};

template<class Archive, class eT>
typename std::enable_if<cereal::traits::is_input_serializable<cereal::BinaryData<eT>, Archive>::value, void>::type
load( Archive & ar, Mat<eT>& m ) {
    uword n_rows_local, n_cols_local, n_elem_local, vec_state_local;
    std::size_t data_size;
    ar( n_rows_local, n_cols_local, n_elem_local, vec_state_local );
    data_size = static_cast< std::size_t >( n_elem_local * sizeof( eT ) );
    m.set_size( n_rows_local, n_cols_local );
    ar( cereal::binary_data( reinterpret_cast< void * const >( const_cast< eT* >( m.memptr() ) ), data_size ) );
};

void TestArmadilloSerialization() {
    arma::mat xx1 = arma::randn( 10, 20 );
    std::ofstream ofs( "test", std::ios::binary );
    cereal::BinaryOutputArchive o( ofs );
    o( xx1 );
    ofs.close();
    // Now load it.
    arma::mat xx2;
    std::ifstream ifs( "test", std::ios::binary );
    cereal::BinaryInputArchive i( ifs );
    i( xx2 );
}

0 个答案:

没有答案