Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crash when calling PyArg_ParseTuple on a Numpy array

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?

like image 834
Mark Morrisson Avatar asked Jun 21 '16 11:06

Mark Morrisson


1 Answers

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.

like image 87
Ilja Everilä Avatar answered Nov 09 '22 12:11

Ilja Everilä