我正在用 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)
最佳答案
在您的 python 减速中为 a、b、c 指定数据类型为 dtype=np.float64。 Double 在 C 语言中是 64 位 float 。像您使用它的方式一样使用 np.array 通常会返回 np.int64。像这样使用 np.array 将返回一个 np.float64
a=np.array([1.,2.,3.])
关于python - 无法正确地将 Numpy 数组转换为 Python 扩展的 c 数组 (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55180959/