[Pyrex] When C owns all references to an object

Greg Ewing greg at cosc.canterbury.ac.nz
Mon Sep 22 05:25:49 CEST 2003


> Another problem I'm facing is when I'm trying to wrapper a function that
> requires a callback.
> 
> The problem, I believe, is that the tuple user_data defined in
> some_function gets garbage collected because Python doesn't know that a
> C api still has a reference to it. Is there a way I can keep this from
> happening without creating some hack list that I just append every
> user_data tuple to just to keep a reference floating around?

You'll have to keep a reference to the callback somewhere for as long
as it's needed, but you should be able to do better than just keeping
every object that's ever been used as a callback around forever.

The callback will typically be associated with some C data structure,
and typically you will have defined an extension type to represent
that structure on the Python side. In that case, you can keep a
reference to the callback as an attribute of the extension type.

By the way, it's not really necessary for the callback to be a tuple
-- all you really need is a callable object. The user can always
arrange for it to have the necessary context by passing a closure or
bound method. (You might still want to allow a tuple for convenience,
though.)

Greg Ewing, Computer Science Dept, +--------------------------------------+
University of Canterbury,	   | A citizen of NewZealandCorp, a	  |
Christchurch, New Zealand	   | wholly-owned subsidiary of USA Inc.  |
greg at cosc.canterbury.ac.nz	   +--------------------------------------+




More information about the Pyrex mailing list