使用python的C扩展模块将双数组从C传递到python时转储了内核

2024-09-29 00:14:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个简单的c代码,它将向python返回一个双数组。我成功地编译了代码,没有出错,并且可以生成.so文件以在python中导入。然而,当我从Python环境调用包装的C函数时,我得到core dump。我附上下面的c代码,这样错误就可以重现了。如果有人指点我,让我明白我错在哪里,导致core dump错误,我将不胜感激?在调试时,我发现错误源在

pyArr = (PyArrayObject*) PyArray_SimpleNewFromData(2, dims, NPY_DOUBLE, ptr);

但我无法解决这个问题。我也尝试过在line 6中使用static double array,但得到了相同的core dump问题。感谢您的帮助。你知道吗

#include <Python.h>
#include <numpy/arrayobject.h>
#include <numpy/ndarrayobject.h>

extern "C" {
    static PyObject* func_wrap(PyObject* , PyObject* args)
    {
    double* ptr;
    ptr = (double *) malloc(4 * sizeof(double));
    *ptr = 1.0; *(ptr+1) = 2.0; *(ptr+2) = 3.0; *(ptr+3) = 4.0;
    PyArrayObject* pyArr;
    npy_intp dims[1];
    dims[0] = 4;
    pyArr = (PyArrayObject*)PyArray_SimpleNewFromData(1, dims, NPY_BYTE, ptr);
    PyArray_ENABLEFLAGS(pyArr, NPY_ARRAY_OWNDATA);  /* numpy array takes the ownership afterwards */
    return Py_BuildValue("O", pyArr);
 }

 static PyMethodDef CppMethods[] = {
      {"func", func_wrap, METH_VARARGS, "returns numpy 1d array"},
      {NULL, NULL, 0, NULL}
  };

 // Define module information
 static struct PyModuleDef mydemo = {
 PyModuleDef_HEAD_INIT,
 "mydemo",
 "mydemo Module",
 -1,
 CppMethods
 };

 // Init function for module
 PyMODINIT_FUNC PyInit_mydemo(void) {
     import_array();
     return PyModule_Create(&mydemo);
 }
}

Tags: 代码corenumpyincludestaticarraydumpdouble