[cairo] API completeness of reference/user_data pairs

Owen Taylor otaylor at redhat.com
Mon Feb 5 08:44:08 PST 2007


On Mon, 2007-02-05 at 11:06 -0500, Behdad Esfahbod wrote:
> On Mon, 2007-02-05 at 09:46 +0800, Steve Chaplin wrote:
> > 
> > The cairo manual section "Creating a language binding / Memory
> > Management",
> > says (regarding the problem of subclassing) "This is not easily
> > fixable
> > without creating memory leaks, and it's probably best to simply forbid
> > deriving from the language objects." - and that's what pycairo does
> > (with the
> > exception of cairo.Context).
> 
> So, anyone knows about the roots of that sentence?  Is it just from
> before the user-data APIs landing in?  Carl?

If you want subclassing to work, then you need to keep the Python (say)
object around even when it is only referenced from cairo, so that:

 cr.set_source(surface)
 surface = cr.get_source()
 surface.my_method()

works. You also, obviously need to keep the cairo surface around when
it is only referenced from Python, so that:

 new MySurface()

works. So, you inherently need a circular reference where Python
references cairo and cairo references Python. There are various things
you can do to to prevent this causing a memory leak, more or less
hackily. PyGTK hooks into the Python garbage collector. Gtk-Perl 
(IIRC) exploits some special properties of how Perl refcounting works.
An older version of perl GTK+ bindings kept a big table of all Perl/GTK+
objects and walked through it in a timeout to find leaked pairs.

GObject now has the concept of toggle refcounts which provide a generic
and relatively clean way of managing the situation, even when the
language garbage collection is opaque (think Java or the CLR). But they
seemed like overkill for cairo, especially since there is no base
object class, so I simply wrote the sentence above.

					- Owen




More information about the cairo mailing list