[Pyrex] Reference count on object assignment

John Arbash Meinel john at arbash-meinel.com
Wed Aug 5 17:36:20 CEST 2009


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Daniele Pianu wrote:
> 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
> 

I'm pretty sure the answer is "it is automatically handled". If you look
at the generated code:

self.obj = <object>obj

is translated roughly as

Py_INCREF(obj);
self.obj = (PyObject *)obj;

So adding Py_INCREF as you have written above should actually be incorrect.

John
=:->
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (Cygwin)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iEYEARECAAYFAkp5pvQACgkQJdeBCYSNAAO+FACfT4ufHe9NMf6K2EocJgnh9Gtv
P48AnR30k5l9TyvBu53qLOT8wBIyjaAt
=KIjQ
-----END PGP SIGNATURE-----



More information about the Pyrex mailing list