Search code examples
pythonnumpypython-c-api

PyArg_ParseTuple SegFaults in CApi


I am writing a code, trying to get used to the C API of NumPy arrays.

#include <Python.h>
#include "numpy/arrayobject.h"
#include <stdio.h>
#include <stdbool.h>


static char doc[] =
"Document";

static PyArrayObject *
    trace(PyObject *self, PyObject *args){

    PyArrayObject *matin;

    if (!PyArg_ParseTuple(args, "O!",&PyArray_Type, &matin))
         return NULL;

    printf("a");
    return matin;
}

static PyMethodDef TraceMethods[] = {
    {"trace", trace, METH_VARARGS, doc},
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC
inittrace(void)
{
    (void) Py_InitModule("trace", TraceMethods);
    import_array();
}

This is a stripped-down version. I just want to be able to get an object of type PyArrayObject and return it back. Unfortunately this gives a SegFault also.

Linux, 64-bit, Python 2.7.1


Solution

  • From the docs:

    O (object) [PyObject *]
    Store a Python object (without any conversion) in a C object pointer. The C program thus receives the actual object that was passed. The object’s reference count is not increased. The pointer stored is not NULL.

    O! (object) [typeobject, PyObject *]
    Store a Python object in a C object pointer. This is similar to O, but...

    You're returning a stolen reference. Increment it first.