首先需要確定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\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++中讀取的數組將不再是原來的數組。需要特別注意。