Reference Counts & Extensions..

Brian Quinlan BrianQ at ActiveState.com
Tue Jun 12 17:13:02 EDT 2001


John wrote:
>     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?  Should I be doing this:
>
>     PyObject *pyObj = PyBuildValue("i", 1);
>     Py_INCREF(pyObj);
>     return pyObj;
>
>     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;

Py_BuildValue returns a new Python object with a reference count of
one. The call to Py_INCREF is not required.

But I don't understand why you were considering increase the reference
count of pyObj to remove a potential memory leak; increasing the
reference count makes the object persist for one more reference count
decrement i.e. you were going the wrong way :-)

If you make pyObj a global then you must increment the reference count
every time you return it to Python.





More information about the Python-list mailing list