python - boost::C++ 中的序列化,Python 中的反序列化

标签 python c++ boost

我用 C++ 生成了一些我想在 Python 程序中访问的数据。我已经弄清楚如何在 C++ 中使用 boost 对二进制文件进行序列化/反序列化,但不知道如何在 Python 中访问数据(无需手动解析二进制文件)。

这是我的序列化 C++ 代码:

/* Save some data to binary file */
template <typename T>
int serializeToBinaryFile( const char* filename, const T& someValue,
                           const vector<T>& someVector )
{
    ofstream file( filename, ios::out | ios::binary | ios::trunc );

    if ( file.is_open() )
    {
        boost::archive::text_oarchive oa(file);

        int sizeOfDataType = sizeof(T);

        oa & sizeOfDataType;
        oa & someValue;
        oa & someVector;

        file.close();

        return 0;
    } else {
        return 1;
    }
}

这是我的反序列化 C++ 代码:

/* Load some data from binary file */
template <typename T>
int deSerializeFromBinaryFile( const char* filename, int& sizeOfDataType,
                               T& someValue, vector<T>& someVector )
{
    ifstream file( filename, ios::in | ios::binary );

    if ( file.is_open() )
    {
        boost::archive::text_iarchive ia(file);

        ia & sizeOfDataType;
        ia & someValue;
        ia & someVector;

        file.close();

        return 0;
    } else {
        return 1;
    }
}

如何将值和 vector 加载到 Python 程序中的对象?

最佳答案

boost 文档提到二进制表示不可移植,甚至不能保证在程序的不同版本之间保持一致这一事实。

您可能想使用 boost::serialization 中可用的 xml 序列化程序,然后使用 python 中的 xml 解析器进行读取。

有关如何执行此操作的说明(和示例)位于此处:http://www.boost.org/doc/libs/1_58_0/libs/serialization/doc/tutorial.html#archives

请注意使用 NVP 宏来命名存档中的项目。

关于python - boost::C++ 中的序列化,Python 中的反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30524145/

相关文章:

c++ - 编织内联类型转换(python)

c++ - 我如何让 main 成为我类(class)的 friend ?

c++ - 正则表达式匹配任何行上的多个 MBCS 字符串

c++ - 用迭代器索引

c++ - 更改命名空间以自定义 boost xml 的标签名称后的反序列化问题

python - 如何在 scikit-learn 中实现多项式逻辑回归?

python - 根据文件扩展名打开语句

c++ - 使用 Boost.Asio 时确保有效对象生命周期的最佳方法是什么?

c++ - 为什么 STL vector 不能包含协程对象?

python - 从二维 numpy 数组中获取 x、y、值一维数组(线性索引)