[pygtk] Reference counting and C callbacks

Nathaniel Smith njs at pobox.com
Sun Sep 9 02:22:57 WST 2007


I need to snoop on some X events that are not wrapped by gdk/pygdk, so
I wrote a wrapper around gdk_window_add_filter.  My wrapper takes a
gtk.gdk.Window and a python callable, and arranges that the callable
gets called each time the window gets the event, using something like
(in pyrex):

--

# Python wrapper for gdk_window_add_filter
def my_gdk_window_add_filter(window, callback):
  gdk_window_add_filter(<GdkWindow*>pygobject_get(window),
                        my_c_callback, <void*>callback)

# C callback, that is passed to gdk_window_add_filter, and responsible
# for then calling back into the real Python callback
cdef GdkFilterReturn my_c_callback(GdkXEvent * xev,
                                   GdkEvent * gdkev,
                                   void * userdata):
  py_callback = <object>userdata
  # ...unpack xev into a python object...
  py_callback(unpacked_event)

--

So that all works great.  My problem now is memory management.

In particular, the python callback leaves the world of python
references.  So obviously I need to INCREF it.  Therefore, I need to
DECREF it eventually.  The time to DECREF it is when the
gtk.gdk.Window is itself destroyed... but is there any way for me to
get at this information?  At the moment I have an unbounded memory
leak as windows are created and destroyed.

-- Nathaniel

-- 
- Don't let your informants burn anything.
- Don't grow old.
- Be good grad students.
  -- advice of Murray B. Emeneau on the occasion of his 100th birthday


More information about the pygtk mailing list