首先需要确定 C++ 和 Python 中变量对应的精度类型,
常用的,
C++int 对应 Pythonnp.intc
C++float 对应 Pythonnp.single
C++double 对应 Pythonnp.double
numpy 数组保存为二进制文件
- import numpy as np
- a = np.array([[1.888,2.8888,3.88888],[4.666,5.6666,6.66666]])
- a = a.astype(np.double)
- a.astype('double').tofile("varr.data")
C++ 读取二进制文件
- #include <iostream>
- #include <fstream>
- using namespace std;
- int main()
- {
- double fnum[2][3] = {0};
- ifstream in("varr.data", iOS::in | iOS::binary);
- in.read((char *) &fnum, sizeof fnum);
- // see how many bytes have been read
- cout << in.gcount() << "bytes read\n";
- for(int j=0; j<3; j++) // show values read from file
- cout << fnum[0][j] << " ";
- in.close();
- return 0;
- }
如果数据类型对应关系错了, 例如把 a.astype('double').tofile("varr.data") 改成 a.astype('float).tofile("varr.data")`,C++ 中读取的数组将不再是原来的数组. 需要特别注意.
来源: http://www.bubuko.com/infodetail-3351985.html