Reference Counts & Extensions..

Martin von Loewis loewis at informatik.hu-berlin.de
Sat Jun 16 13:32:38 EDT 2001


"John" <john.thai at dspfactory.com> writes:

>     I'm writing an extension module and in my functions I return something
> like:
> 
>     return Py_BuildValue("i", 1);
> 
>     Will this cause a memory leak?

No, extension methods always return new references, so does
Py_BuildValue. In this specific case, I'd recommend to use
PyInt_FromLong, though; it's faster and says more directly what you
want to return

>     Also, what if I make pyObj a global variable, can I then use the first
> method since the reference will be borrowed, like so:
> 
>     return pyObj;

No, you must Py_INCREF(pyObj). You cannot return borrowed references;
the interpreter will decref your result when it is not longer needed,
releasing your object. This will make pyObj an invalid pointer.

Regards,
Martin




More information about the Python-list mailing list