About extending NumPy with c
Hello i want to write a c function that receive and process a numpy array. to do so, i'm following this tutorial http://numpy.scipy.org/numpydoc/numpy-13.html as a start, i copy pasted the "A Simple Example" from the tutorial and compiled the module as usual with no errors/warnings. however, when trying to run the function on a legal numpy array, i'm getting an error message: "python.exe has encountered a problem and needs to close, send, dont send etc' i've narrowed it down and it happens when running this line if (!PyArg_ParseTuple(args, "O!", &PyArray_Type, &array)) any ideas how to solve it? thanks here's my complete c file: #include <python.h> #include <numeric/arrayobject.h> static PyObject *trace(PyObject *self, PyObject *args) { PyArrayObject *array; double sum; int i, n; if (!PyArg_ParseTuple(args, "O!", &PyArray_Type, &array)) return NULL; if (array->nd != 2 || array->descr->type_num != PyArray_DOUBLE) { PyErr_SetString(PyExc_ValueError, "array must be two-dimensional and of type float"); return NULL; } n = array->dimensions[0]; if (n > array->dimensions[1]) n = array->dimensions[1]; sum = 0.; for (i = 0; i < n; i++) sum += *(double *)(array->data + i*array->strides[0] + i*array->strides[1]); return PyFloat_FromDouble(sum); } static PyMethodDef foo_methods[] = { { "trace", trace, METH_VARARGS, NULL}, { NULL, NULL, 0, NULL } }; PyMODINIT_FUNC initfoo() { Py_InitModule3("foo", foo_methods, "bla bla"); }
On 1/13/07, asaf david <asafdav2@gmail.com> wrote:
Hello i want to write a c function that receive and process a numpy array. to do so, i'm following this tutorial http://numpy.scipy.org/numpydoc/numpy-13.html as a start, i copy pasted the "A Simple Example" from the tutorial and compiled the module as usual with no errors/warnings. however, when trying to run the function on a legal numpy array, i'm getting an error message: "python.exe has encountered a problem and needs to close, send, dont send etc' i've narrowed it down and it happens when running this line
if (!PyArg_ParseTuple(args, "O!", &PyArray_Type, &array))
any ideas how to solve it? thanks Well, the problem is pretty basic, but you would have a really hard time to find it.... The problem happens at that line, but not because of that line... It would happen with any call to the numpy C API (the first one for that matter).
PyMODINIT_FUNC initfoo() { Py_InitModule3("foo", foo_methods, "bla bla"); }
Here is your problem ! in your init function, you HAVE to call import_array(): PyMODINIT_FUNC initfoo() { Py_InitModule("foo", foo_methods, "bla bla"); import_array(); } This initializes the numpy C API. Without this call, all functions of the numpy C API are actually dangling pointers, and do not point to any valid function. David
participants (2)
-
asaf david -
David Cournapeau