releasing the reference returned by PyLong_FromLong, PyString_FromString & friends

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Dec 13 15:16:22 EST 2007


En Thu, 13 Dec 2007 08:50:09 -0300, grbgooglefan <ganeshborse at gmail.com>  
escribi�:

> I am having a object tuple created at application startup. This tuple
> I pass on to a python function in call to:
> PyObject_CallObject(pcatInfo->pPyEvalFunction,pTuple);
>
> For setting the values in this tuple, I am using PyLong_FromLong,
> PyString_FromString & friends functions.
>     PyTuple_SetItem(pTuple,nCtr,PyString_FromString(szOrdValue));
>
> My worry is that I will be doing this operation lot many times in the
> active duration of my application. During this time I do not want to
> delete the tuple (pTuple) object passed to PyObject_CallObject, to
> avoid the time taken for creating the object every time.

Tuples are supposed to be immutable so in principle you should not do  
that. You must be absolute and possitively sure that the called function  
may not store its argument tuple in any way. At least check that its  
reference count is still 1 before modifying it.
Tuples are rather optimized, they take exactly as much memory as required,  
not more. Creating a tuple is not expensive at all. Why do you think you  
gain something by reusing a tuple? PyString_FromString is potentially much  
slower than that.

> But this poses another problem. Every call I make to PyLong_FromLong,
> PyString_FromString & friends & functions, they return references.
> How do we release the references or objects returned by these
> functions?

In general, using Py_DECREF. If you are using the C API you should already  
know that. Getting the reference count right is very important: err by +1  
and memory will never be released; err by -1 and Python may crash (even on  
unrelated places).
See section 1.10 on the "Extending and embedding" reference, and section 3  
on the "Python/C API".

Note that PyTuple_SetItem already decrements the reference count of the  
replaced item, so if you use PyTuple_SetItem with a new reference, no  
additional adjustment is required.

-- 
Gabriel Genellina




More information about the Python-list mailing list