I wrote a simple Python extension function in C that just reads a Numpy array and it crashes.
static PyObject *test(PyObject *self, PyObject *args)
{
PyArrayObject *array = NULL;
if (!PyArg_ParseTuple(args, "O!", &PyArray_Type, &array)) // Crash
return NULL;
return Py_BuildValue("d", 0);
}
Here is how it is called:
l = np.array([1,2,3,1,2,2,1,3])
print("%d" % extension.test(l))
What's wrong with my code?
I think the error is in the code you did not include in your example: have you remembered to call import_array()
in your module init function:
... this subroutine must also contain calls to import_array() and/or import_ufunc() depending on which C-API is needed. Forgetting to place these commands will show itself as an ugly segmentation fault (crash) as soon as any C-API subroutine is actually called.
http://docs.scipy.org/doc/numpy-1.10.1/user/c-info.how-to-extend.html#required-subroutine
I copied your example verbatim and added (using python 3)
PyMODINIT_FUNC
PyInit_numpytest(void)
{
import_array();
return PyModule_Create(&numpytest);
}
and the example ran without issues. Removing the call on the other hand produces a crash.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With