What exactly are GLib and GObject?

RanRag picture RanRag · Jul 2, 2012 · Viewed 14.4k times · Source

I have been looking into the source code of python-mpdor and it mentions that it is

gobject-based, for easy event handling (in the high-level client class).

Can someone explain to me in simple terms what exactly are Glib and GObject and how do they interact with each other and what role it plays in event handling.

I tried searching for Glib and GObject but I didn't found any basic explanation for it. All the explanations I found are very technical and by technical I mean not suitable for a beginner.

Also, can someone point to some beginner tutorials/articles about Glib and GObject.

Answer

Micah Carrick picture Micah Carrick · Jul 3, 2012

GLib and GOBject are 2 separate C libraries from which the GTK+ GUI toolkit is built (among other things).

Since C is a lower-level language, GLib provides a lot of basic functionality like those utilities similar to what is built-in with Python (file input/output, string manipulation, memory management, threading, etc.).

Since C is not an object-oriented language, GObject provides a C-based object system which includes properties and inheritance (again, built into Python already). In Python, you rarely use GLib directly (because Python has most of that functionality built-in) but GObject is dependent upon GLib.

All GObject-based libraries are designed to support language bindings to other languages such as Python.

To the point of your question, GObject provides an event system known as "signals". Any object derived from GObject can "emit" signals to send notifications of an event occurring. The MPDProtocolClient class in python-mpdor is derived from GObject and thus it can emit signals. Applications "connect" functions to these signals. F

For example, the README shows this example:

import gobject
import mpdor

def notify(client, vol):
    print "mpd volume is at ", vol + "%"

client = mpdor.client.Client()
client.connect("mixer-change", notify)
gobject.MainLoop().run()

In this case, the function named notify is "connected" to the "mixer-change" signal which means that function will be called any time the client "emits" that signal. The gobject.MainLoop().run() call enters a "main event loop" (basically an infinite loop) which is a standard concept in event-driven programming.

You probably won't find a lot of GObject/Python tutorials, however, if you learn a little bit of Python/GTK+ basics then you'll likely get a grasp of the concepts of the event loop, signals, and signal callbacks. (It looks like python-mpdor is using GTK+ 2 which would be PyGTK as opposed to newer GTK+ 3 which is PyGObject).

Good luck.