I have a problem because I did not realy get yet when do Py_INCREF or to Py_DECREF.
I build a class type that covers a PyObject*-Array. Now I wrote a function like that:

static PyObject *
get_first(MyObject *self) {
    PyObject *res = NULL;
    if (!self->size)
        return NULL;

    res = self->items[0];
    // Py_INCREF(res);
    return res;

I don't really know why I should use Py_INCREF(res) but if I don't do it I'll get a segmentation fault after calling the function several times. This doesn't happen if i put in a Py_INCREF(res).
I thought I don't have to care about what the user does with the result. Do I always have to Py_INCREF my results???

7 Years
Discussion Span
Last Post by sneek

Yes I think that you must always incref the results. Also consider using Py_XINCREF and Py_XDECREF which handle the case where you pass a null pointer.
A good idea is to test your code with the help of the sys.getrefcount() function. For example

>>> class A:
...  pass
>>> a = A()
>>> sys.getrefcount(a)
>>> L =[a, a, a]
>>> sys.getrefcount(a)

With this, you can check the refcounts before and after various calls to your C functions.

Edited by Gribouillis: n/a


Wow, this is what I call a quick answer :)
Thanks a lot and also for that sys.getrefcount hint.
May you tell me more detailed why it's necessary to perform Py_INCREF with every return?

Edited by sneek: n/a


First, you must read this reference counting.
Why do you need to incref results ? First argument, that's how code is usually written. When a function must return None, you write

    return Py_None;

Second argument: python expects a new reference. If you don't incref, python will decref and you end up with a segfault.


Okay thanks another time. I already read the refcount manual but I did not get that return thing :S

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.