Re: Reference count on object assignment
John Arbash Meinel <[email protected]> Wed, 05 Aug 2009 10:36:20 -0500
| Newsgroups | gmane.comp.python.pyrex |
|---|---|
| Message-ID | <[email protected]> |
-----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 =3D <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 =3D <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 =3D <object>obj is translated roughly as Py_INCREF(obj); self.obj =3D (PyObject *)obj; So adding Py_INCREF as you have written above should actually be incorrect. John =3D:-> -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (Cygwin) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/ iEYEARECAAYFAkp5pvQACgkQJdeBCYSNAAO+FACfT4ufHe9NMf6K2EocJgnh9Gtv P48AnR30k5l9TyvBu53qLOT8wBIyjaAt =3DKIjQ -----END PGP SIGNATURE-----