[Pyrex] Reference count on object assignment

Daniele Pianu muogoro at gmail.com
Wed Aug 5 11:19:04 CEST 2009


Hi all,
I've a simple question about the reference count automatically
performed by Cython/Pyrex. I've a cdef function in an ipotetic
extension type:

......

cdef TakeObject( self, void* obj ):
 self.obj = <object>obj
 Py_INCREF( self.obj )

.......

The function receives a void pointer that I know it's always a pointer
to a Python object. The extension type must mantain a reference to
this object in its obj attribute, so, I perform
the assignment "self.obj = <object>obj". The reference should be valid
after the object pointed by the obj method argument is deref-counted.
For this reason, I increment manually the reference count of the same
object (now pointed by the obj instance attribute too). The question
is: in an assignment where a <object> cast is performed, is the
reference count automatically handled? Or do I need to manually
increment-decrement the reference count as in the example above? And,
if self.obj previously pointed to another object whose reference
counted was incremented, do I have to decrement the reference count to
avoid a possible memory leak? I've checked a bit the code and it seems
the, first than the assignment is done, the self.obj ref count is
decremented, but I've not understood if it's incremented too after the
new assignment.

Thanks for any advice,
Daniele



More information about the Pyrex mailing list