我用 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/