我正在用 c++ 开发一个 Python 扩展。但是,我对 C++ 真的很生疏,似乎没有必要的经验来解决这个问题。我正在尝试读取 numpy 数组,进行我想做的计算,然后返回一个 numpy 数组。我遇到的问题是将numpy数组转换为'c格式'的普通Double数组。我尝试了两种方法来转换数据,但都得到相同的结果,当我打印出数组时似乎存储了内存位置,而不是实际值
这是带有一些注释的代码。
static PyObject* mymodule_function(PyObject *self, PyObject *args){
PyArrayObject *x_obj,*y_obj;
double *x, *y;
if (!PyArg_ParseTuple(args, "O!O!", &PyArray_Type, &x_obj,&PyArray_Type, &y_obj)) return NULL;
if (NULL == x_obj) return NULL;
if (NULL == y_obj) return NULL;
npy_intp N = PyArray_DIM(x_obj, 0);
std::cout << int(N) << std::endl; //Correctly prints out size of array
//method 1 I tried to convert data
x = (double*)x_obj->data;
//method 2 that I tried
y = (double*)PyArray_DATA(y_obj);
// Debug printing.
for (int i = 0; i < (int)N; i ++){
std::cout << x[i] << std::endl;
std::cout << y[i] << std::endl;
}
//prints out array correctly
double z[N];
myfunction(x,y,z,(int)N);
// Debug printing.
for (int i = 0; i < (int)N; i ++){
std::cout << z[i] << std::endl;
}
//prints out array correctly
npy_intp dims[1];
dims[0] = N;
PyObject *pyArray = PyArray_SimpleNewFromData(1, dims, NPY_DOUBLE, z);
PyObject *ret = Py_BuildValue("O", pyArray);
return ret;
}
和我使用的 Python 代码:
import numpy as np
import mymodule as mm
a = np.array([1,2,3],dtype=np.float64)
b = np.array([4,5,6],dtype=np.float64)
c = np.zeros(shape=(1,3),dtype=np.float64)
c = mm.function(a,b)
print(c)