繁体   English   中英

无法将Numpy数组正确转换为Python扩展(C ++)的C数组

[英]Can't correctly convert Numpy array to c array for Python Extension (c++)

我正在用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减速度中为dtype = np.float64指定a,b,c的数据类型。 C语言中的Double是64位浮点数。 像使用它一样使用np.array通常会返回np.int64。 像这样使用np.array将返回np.float64

a=np.array([1.,2.,3.])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM