首先需要确定C++和Python中变量对应的精度类型,
https://docs.scipy.org/doc/numpy/user/basics.types.html#array-types-and-conversions-between-types
常用的,
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
";
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++中读取的数组将不再是原来的数组。需要特别注意。