Writing Perl bindings for GObject based libraries

potyl on 2009-09-24T18:27:37

I have in CPAN two modules that provide Perl bindings over two existing C libraries: Gtk2::Unique and Champlain. These two modules both wrap C libraries that use Glib's GObject framework. I don't want to go too much in the details of explaining how GObject works, so I will just keep it brief. What's important to know is that the library provides and object-oriented framework for C that's easy to map to other languages through bindings (Perl, Python, Java, C++, etc). It provides classes, interfaces, a generic type system, memory management for objects, signals and even inheritance. You might not know too much about GObjects but you might be using them indirectly as it is the basis for Gtk2 and the Gnome desktop.

GObject and Glib have already Perl bindings: Glib. The Perl module on it self doesn't look so impressive as other Perl modules in CPAN offer the same functionality, nevertheless the module is capital. What makes it so unique is that it provides all the basis for the GObject framework. All the hard work of providing a mapping between GObjects's data structures, runtime, memory management and type system to Perl is covered by Glib!

Thanks to Glib's bindings, writing Perl bindings for a GObject based library is very easy. Most of the time all that's involved is to provide a map file that describes the C data structures (Objects, Interfaces, ect), to map their C names with Perl package names, to provide the prototypes of the C functions to bind in the XS files and to write the unit tests of course. That's it! Perl's Glib module will take care of the rest as it provides the utilities for compiling and linking the C code for us. It really is that simple.

The GObject framework is still evolving and gets new features. One that's very promising is introspection. This means that in a near future writing Perl bindings for a GObject based library will be almost if not automatic. And this future might not be so far as some work has been already made in order to give us even easier wrappers: Introspection for GTK2-Perl.