Crash using Python 2.0 Extension

Ken Koller kkoller at newfocus.com
Thu Jan 25 15:21:52 EST 2001


Thanks, I knew I was missing something. And I was looking at some of the
source, it's just that it was pretty late and I was burned out. I should have
caught that though.

Fredrik Lundh wrote:

> Ken Koller wrote:
> > I originally wrote the routine below to return Py_None, but the
> > interpretter would crash after calling the routine several times (maybe
> > 100-200) in a row.
>
> you mean like
>
>     static PyObject * pt_pSetModule(PyObject * self, PyObject * args)
>     {
>         return Py_None;
>     }
>
> this doesn't work -- Python expects your function to own a
> reference to the object you'll returning, and will decrement
> the reference counter once it's done with the return value.
> When the return value reaches zero, the None object is
> removed, and anything can happen.
>
> (in a stock interpreter, there already are 100-200 references
> to None when your program starts running. sys.getrefcount(None)
> will give you the exact number for your setup).
>
> But if you look in the library sources (*always* do this when you
> cannot figure out how to use the C API), you'll notice that many
> functions/methods do return Py_None -- but they all do one very
> important thing before doing so:
>
>     Py_INCREF(Py_None); /* get another reference to None */
>     return Py_None; /* return an owned reference */
>
> for more info, see:
> http://www.python.org/doc/current/ext/refcounts.html
> (especially "ownership rules")
>
> Cheers /F
>
> <!-- (the eff-bot guide to) the standard python library:
> http://www.pythonware.com/people/fredrik/librarybook.htm
> -->




More information about the Python-list mailing list