[Numpy-discussion] Complete and build the example from the "Using Numpy C-API" documentation.

Pauli Virtanen pav@iki...
Wed Jul 21 03:14:20 CDT 2010


Tue, 20 Jul 2010 18:04:42 -0500, Warren Weckesser wrote:
[clip]   
> I've made some progress, and now I'm getting a bus error. With the
> following extension module, calling example.foo results in a bus error,
> regardless of the arguments given.  The error occurs in the call to
> PyArg_ParseTuple.  I'm using same format string as in the example in the
> numpy docs, "O!".  Any ideas?
> 
> -----
> #include <stdio.h>
> #include "Python.h"
> #include "numpy/arrayobject.h"
> 
> static PyObject *foo_wrap(PyObject *dummy, PyObject *args) {
>     PyObject *arg1 = NULL;
> 
>     printf("boo\n");
>     if (!PyArg_ParseTuple(args, "O!", &PyArray_Type, &arg1)) {
>         printf("bad\n");
>         return NULL;
>     }
>     printf("here\n");
>     return Py_None;
> }

You need to INCREF the None return value (but that won't cause a crash 
here).

> static PyMethodDef wrappers[] = {
>     {"foo", foo_wrap, METH_VARARGS, "just a test"}, {NULL, NULL, 0,
>     NULL}        /* Sentinel */
> };
> 
> PyMODINIT_FUNC
> initexample(void)
> {
>     (void) Py_InitModule("example", wrappers);
> }

You need to call import_array(); in the init function. Otherwise, 
PyArray_Type probably won't be initialized. This can cause a crash.

-- 
Pauli Virtanen



More information about the NumPy-Discussion mailing list