【发布时间】:2019-08-06 10:28:19
【问题描述】:
我正在用 c++ 开发一个 Python 扩展。但是,我对 C++ 真的很生疏,似乎没有必要的经验来解决这个问题。我正在尝试读取 numpy 数组,进行我想做的计算,然后返回一个 numpy 数组。我遇到的问题是将numpy数组转换为'c格式'的普通Double数组。我尝试了两种方法来转换数据,但都得到相同的结果,似乎在我打印出数组时存储了内存位置,而不是实际值
这是带有一些 cmets 的代码。
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。 C 语言中的 Double 是 64 位浮点数。 np.array 通常返回 np.int64。
-
哦不 :( 确实是问题所在。谢谢!
-
好的。将升级回答。
-
目前虽然仍面临另一端的问题。当我读出我的数组 c 时,它仍然像以前一样打印出来。打印(c):[2.70641052e-312 -4.96427367e+193 2.71209304e-312]。但是,在我返回我的 c++ 函数之前打印出 Z 会正确打印出结果。我将原来的帖子更新为当前代码
-
没关系,使用这样的打印语句似乎是个问题。
标签: python c++ arrays numpy python-extensions