I am writing a simple c code that will return a double array to python. I compiled the code successfully with out error and can generate .so file to import in python. However when I call the wrapped C function from Python environment I get core dump. I am attaching the c code below so that the error can be reproduced. I would be highly obliged if anyone directs me to point me to understand where am I going wrong which results in core dump error? While debuging I found that the source of the error is in the line
pyArr = (PyArrayObject*) PyArray_SimpleNewFromData(2, dims, NPY_DOUBLE, ptr);
yet I am unable to fix the issue. I also tried with static double array in line 6 but got same core dump issue. Any help is appreciated.
#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);
}
}