Make it a library
In this part of the tutorial, we'll move the TutGreeter class to its own shared library, libtut for easy reuse from all our applications with greeting needs.
The libtool utility is a good way of creating shared and dynamic libraries in a portable way. Usually, this shell script is included with the distribution of any package using it, but you can also use a system installed version. On Debian-based systems, use sudo apt-get install libtool to install it. Then you can compile and link the library with:
$ libtool compile gcc `pkg-config --cflags gobject-2.0` \ -g -c tut-greeter.c -o tut-greeter.lo $ libtool link gcc `pkg-config --libs gobject-2.0` \ -rpath /usr/local/lib \ tut-greeter.lo -o libtutorial.la
libtool is a bit picky about some things, like the order of the arguments to gcc, but the above works for me.
The call g-ir-scanner is similar to the previous case, exchanging --program for --library. Run g-ir-compiler in just the same way.
$ g-ir-scanner tut-greeter.[ch] \ --library=tutorial \ `pkg-config --cflags gobject-2.0` --include=GObject-2.0 \ --namespace=Tut --nsversion=0.1 --output=Tut-0.1.gir $ g-ir-compiler Tut-0.1.gir --output=Tut-0.1.typelib
Note that when g-ir-scanner scans a library, it compiles a stub program to call the gi_repository_dump function. It then needs to find the libtutorial.so shared library file, which libtool places in the .libs directory. Since g-ir-scanner uses libtool itself, this happens to just work. However, for the following steps to work we need to set some environment variables so that gjs and Python can find the library and the typelib file (as we did before):
$ export LD_LIBRARY_PATH=`pwd`/.libs:$LD_LIBRARY_PATH $ export GI_TYPELIB_PATH=`pwd`
Now, we're ready and can easily access the class from a JavaScript. We can do the following to do the same job as our main.c did:
$ gjs main.js Hello, JavaScript programmer!
With PyGObject installed, we can use the class from a Python interpreter:
$ python Python 2.7.4 (default, Apr 19 2013, 18:32:33) [GCC 4.7.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from gi.repository import Tut >>> greeter = Tut.Greeter(greetee = "Python programmer") >>> greeter.greet() Hello, Python programmer!
Here's a Lua one-liner, using the lgi bindings:
$ lua -e 'require("lgi").require("Tut").Greeter { greetee = "Lua programmer" }:greet()' Hello, Lua programmer!
Finally, a little Ruby program using the ruby-gir-ffi bindings:
require 'gir_ffi' GirFFI.setup :Tut obj = Tut::Greeter.new obj.set_property 'greetee', 'Ruby programmer' obj.greet
There are many other languages you can use, like C#, Vala, Java, Guile and more; see this page for bindings.
This tutorial has barely scratched the surface of what you can do with GObject Introspection, but I hope it has wet your appetite!