1Glib::Object::IntrospecUtsieorn(C3o)ntributed Perl DocumGelnitba:t:iOobnject::Introspection(3)
2
3
4
6 Glib::Object::Introspection - Dynamically create Perl language bindings
7
9 use Glib::Object::Introspection;
10 Glib::Object::Introspection->setup(
11 basename => 'Gtk',
12 version => '3.0',
13 package => 'Gtk3');
14 # now GtkWindow, to mention just one example, is available as
15 # Gtk3::Window, and you can call gtk_window_new as Gtk3::Window->new
16
18 Glib::Object::Introspection uses the gobject-introspection and libffi
19 projects to dynamically create Perl bindings for a wide variety of
20 libraries. Examples include gtk+, webkit, libsoup and many more.
21
23 To allow Glib::Object::Introspection to create bindings for a library,
24 the library must have installed a typelib file, for example
25 "$prefix/lib/girepository-1.0/Gtk-3.0.typelib". In your code you then
26 simply call "Glib::Object::Introspection->setup" with the following
27 key-value pairs to set everything up:
28
29 basename => $basename
30 The basename of the library that should be wrapped. If your
31 typelib is called "Gtk-3.0.typelib", then the basename is 'Gtk'.
32
33 version => $version
34 The particular version of the library that should be wrapped, in
35 string form. For "Gtk-3.0.typelib", it is '3.0'.
36
37 package => $package
38 The name of the Perl package where every class and method of the
39 library should be rooted. If a library with basename 'Gtk'
40 contains an class 'GtkWindow', and you pick as the package 'Gtk3',
41 then that class will be available as 'Gtk3::Window'.
42
43 The Perl wrappers created by "Glib::Object::Introspection" follow the
44 conventions of the Glib module and old hand-written bindings like Gtk2.
45 You can use the included tool "perli11ndoc" to view the documentation
46 of all installed libraries organized and displayed in accordance with
47 these conventions. The guiding principles underlying the conventions
48 are described in the following.
49
50 Namespaces and Objects
51 The namespaces of the C libraries are mapped to Perl packages according
52 to the "package" option specified, for example:
53
54 gtk_ => Gtk3
55 gdk_ => Gtk3::Gdk
56 gdk_pixbuf_ => Gtk3::Gdk::Pixbuf
57 pango_ => Pango
58
59 Classes, interfaces and boxed and fundamental types get their own
60 namespaces, in a way, as the concept of the GType is completely
61 replaced in the Perl bindings by the Perl package name.
62
63 GtkButton => Gtk3::Button
64 GdkPixbuf => Gtk3::Gdk::Pixbuf
65 GtkScrolledWindow => Gtk3::ScrolledWindow
66 PangoFontDescription => Pango::FontDescription
67
68 With this package mapping and Perl's built-in method lookup, the
69 bindings can do object casting for you. This gives us a rather
70 comfortably object-oriented syntax, using normal Perl object semantics:
71
72 in C:
73 GtkWidget * b;
74 b = gtk_check_button_new_with_mnemonic ("_Something");
75 gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (b), TRUE);
76 gtk_widget_show (b);
77
78 in Perl:
79 my $b = Gtk3::CheckButton->new_with_mnemonic ('_Something');
80 $b->set_active (1);
81 $b->show;
82
83 You see from this that cast macros are not necessary and that you don't
84 need to type namespace prefixes quite so often, so your code is a lot
85 shorter.
86
87 Flags and Enums
88 Flags and enum values are handled as strings, because it's much more
89 readable than numbers, and because it's automagical thanks to the GType
90 system. Values are referred to by their nicknames; basically, strip
91 the common prefix, lower-case it, and optionally convert '_' to '-':
92
93 GTK_WINDOW_TOPLEVEL => 'toplevel'
94 GTK_BUTTONS_OK_CANCEL => 'ok-cancel' (or 'ok_cancel')
95
96 Flags are a special case. You can't (sensibly) bitwise-or these
97 string-constants, so you provide a reference to an array of them
98 instead. Anonymous arrays are useful here, and an empty anonymous
99 array is a simple way to say 'no flags'.
100
101 FOO_BAR_BAZ | FOO_BAR_QUU | FOO_BAR_QUUX => [qw/baz quu qux/]
102 0 => []
103
104 In some cases you need to see if a bit is set in a bitfield; methods
105 returning flags therefore return an overloaded object. See Glib for
106 more details on which operations are allowed on these flag objects, but
107 here is a quick example:
108
109 in C:
110 /* event->state is a bitfield */
111 if (event->state & GDK_CONTROL_MASK) g_printerr ("control was down\n");
112
113 in Perl:
114 # $event->state is a special object
115 warn "control was down\n" if $event->state & "control-mask";
116
117 But this also works:
118
119 warn "control was down\n" if $event->state * "control-mask";
120 warn "control was down\n" if $event->state >= "control-mask";
121 warn "control and shift were down\n"
122 if $event->state >= ["control-mask", "shift-mask"];
123
124 Memory Handling
125 The functions for ref'ing and unref'ing objects and free'ing boxed
126 structures are not even mapped to Perl, because it's all handled
127 automagically by the bindings. Objects will be kept alive so long as
128 you have a Perl scalar pointing to it or the object is referenced in
129 another way, e.g. from a container.
130
131 The only thing you have to be careful about is the lifespan of non
132 reference counted structures, which means most things derived from
133 "Glib::Boxed". If it comes from a signal callback it might be good
134 only until you return, or if it's the insides of another object then it
135 might be good only while that object lives. If in doubt you can
136 "copy". Structs from "copy" or "new" are yours and live as long as
137 referred to from Perl.
138
139 Callbacks
140 Use normal Perl callback/closure tricks with callbacks. The most
141 common use you'll have for callbacks is with the Glib "signal_connect"
142 method:
143
144 $widget->signal_connect (event => \&event_handler, $user_data);
145 $button->signal_connect (clicked => sub { warn "hi!\n" });
146
147 $user_data is optional, and with Perl closures you don't often need it
148 (see "Persistent variables with closures" in perlsub).
149
150 The userdata is held in a scalar, initialized from what you give in
151 "signal_connect" etc. It's passed to the callback in usual Perl "call
152 by reference" style which means the callback can modify its last
153 argument, ie. $_[-1], to modify the held userdata. This is a little
154 subtle, but you can use it for some "state" associated with the
155 connection.
156
157 $widget->signal_connect (activate => \&my_func, 1);
158 sub my_func {
159 print "activation count: $_[-1]\n";
160 $_[-1] ++;
161 }
162
163 Because the held userdata is a new scalar there's no change to the
164 variable (etc.) you originally passed to "signal_connect".
165
166 If you have a parent object in the userdata (or closure) you have to be
167 careful about circular references preventing parent and child being
168 destroyed. See "Two-Phased Garbage Collection" in perlobj about this
169 generally. Toplevel widgets like "Gtk3::Window" always need an
170 explicit "$widget->destroy" so their "destroy" signal is a good place
171 to break circular references. But for other widgets it's usually
172 friendliest to avoid circularities in the first place, either by using
173 weak references in the userdata, or possibly locating a parent
174 dynamically with "$widget->get_ancestor".
175
176 Exception handling
177 Anything that uses GError in C will "croak" on failure, setting $@ to a
178 magical exception object, which is overloaded to print as the returned
179 error message. The ideology here is that GError is to be used for
180 runtime exceptions, and "croak" is how you do that in Perl. You can
181 catch a croak very easily by wrapping the function in an eval:
182
183 eval {
184 my $pixbuf = Gtk3::Gdk::Pixbuf->new_from_file ($filename);
185 $image->set_from_pixbuf ($pixbuf);
186 };
187 if ($@) {
188 print "$@\n"; # prints the possibly-localized error message
189 if (Glib::Error::matches ($@, 'Gtk3::Gdk::Pixbuf::Error',
190 'unknown-format')) {
191 change_format_and_try_again ();
192 } elsif (Glib::Error::matches ($@, 'Glib::File::Error', 'noent')) {
193 change_source_dir_and_try_again ();
194 } else {
195 # don't know how to handle this
196 die $@;
197 }
198 }
199
200 This has the added advantage of letting you bunch things together as
201 you would with a try/throw/catch block in C++ -- you get cleaner code.
202 By using Glib::Error exception objects, you don't have to rely on
203 string matching on a possibly localized error message; you can match
204 errors by explicit and predictable conditions. See Glib::Error for
205 more information.
206
207 Output arguments, lists, hashes
208 In C you can only return one value from a function, and it is a common
209 practice to modify pointers passed in to simulate returning multiple
210 values. In Perl, you can return lists; any functions which modify
211 arguments are changed to return them instead.
212
213 Arguments and return values that have the types GList or GSList or
214 which are C arrays of values will be converted to and from references
215 to normal Perl arrays. The same holds for GHashTable and references to
216 normal Perl hashes.
217
218 Object class functions
219 Object class functions like "Gtk3::WidgetClass::find_style_propery" can
220 be called either with a package name or with an instance of the
221 package. For example:
222
223 Gtk3::WidgetClass::find_style_property ('Gtk3::Button', 'image-spacing')
224
225 my $button = Gtk3::Button->new;
226 Gtk3::WidgetClass::find_style_property ($button, 'image-spacing')
227
228 Overriding virtual functions
229 When subclassing a gtk+ class or when implementing a gtk+ interface
230 with Glib::Object::Subclass, you can override any virtual functions
231 that the class has by simply defining sub routines with names obtained
232 by capitalizing the original names of the virtual functions. So, for
233 example, if you implement a custom subclass of "Gtk3::CellRenderer" and
234 want to override its virtual function "render", you provide a sub
235 routine with the name "RENDER" in your package.
236
237 sub RENDER {
238 my ($cell, $cr, $widget, $background_area, $cell_area, $flags) = @_;
239 # do something
240 }
241
243 "Glib::Object::Introspection->setup"
244 "Glib::Object::Introspection->setup" takes a few optional arguments
245 that augment the generated API:
246
247 search_path => $search_path
248 A path that should be used when looking for typelibs. If you use
249 typelibs from system directories, or if your environment contains a
250 properly set "GI_TYPELIB_PATH" variable, then this should not be
251 necessary.
252
253 name_corrections => { auto_name => new_name, ... }
254 A hash ref that is used to rename functions and methods. Use this
255 if you don't like the automatically generated mapping for a
256 function or method. For example, if "g_file_hash" is automatically
257 represented as "Glib::IO::file_hash" but you want
258 "Glib::IO::File::hash" then pass
259
260 name_corrections => {
261 'Glib::IO::file_hash' => 'Glib::IO::File::hash'
262 }
263
264 class_static_methods => [ function1, ... ]
265 An array ref of function names that you want to be treated as
266 class-static methods. That is, if you want be able to call
267 "Gtk3::Window::list_toplevels" as "Gtk3::Window->list_toplevels",
268 then pass
269
270 class_static_methods => [
271 'Gtk3::Window::list_toplevels'
272 ]
273
274 The function names refer to those after name corrections.
275
276 flatten_array_ref_return_for => [ function1, ... ]
277 An array ref of function names that return an array ref that you
278 want to be flattened so that they return plain lists. For example
279
280 flatten_array_ref_return_for => [
281 'Gtk3::Window::list_toplevels'
282 ]
283
284 The function names refer to those after name corrections.
285 Functions occurring in "flatten_array_ref_return_for" may also
286 occur in "class_static_methods".
287
288 handle_sentinel_boolean_for => [ function1, ... ]
289 An array ref of function names that return multiple values, the
290 first of which is to be interpreted as indicating whether the rest
291 of the returned values are valid. This frequently occurs with
292 functions that have out arguments; the boolean then indicates
293 whether the out arguments have been written. With
294 "handle_sentinel_boolean_for", the first return value is taken to
295 be the sentinel boolean. If it is true, the rest of the original
296 return values will be returned, and otherwise an empty list will be
297 returned.
298
299 handle_sentinel_boolean_for => [
300 'Gtk3::TreeSelection::get_selected'
301 ]
302
303 The function names refer to those after name corrections.
304 Functions occurring in "handle_sentinel_boolean_for" may also occur
305 in "class_static_methods".
306
307 use_generic_signal_marshaller_for => [ [package1, signal1,
308 [arg_converter1]], ... ]
309 Use an introspection-based generic signal marshaller for the signal
310 "signal1" of type "package1". If given, use the code reference
311 "arg_converter1" to convert the arguments that are passed to the
312 signal handler. In contrast to Glib's normal signal marshaller,
313 the generic signal marshaller supports, among other things, pointer
314 arrays and out arguments.
315
316 reblessers => { package => \&reblesser, ... }
317 Tells G:O:I to invoke reblesser whenever a Perl object is created
318 for an object of type package. Currently, this only applies to
319 boxed unions. The reblesser gets passed the pre-created Perl
320 object and needs to return the modified Perl object. For example:
321
322 sub Gtk3::Gdk::Event::_rebless {
323 my ($event) = @_;
324 return bless $event, lookup_real_package_for ($event);
325 }
326
327 "Glib::Object::Introspection->invoke"
328 To invoke specific functions manually, you can use the low-level
329 "Glib::Object::Introspection->invoke".
330
331 Glib::Object::Introspection->invoke(
332 $basename, $namespace, $function, @args)
333
334 · $basename is the basename of a library, like 'Gtk'.
335
336 · $namespace refers to a namespace inside that library, like
337 'Window'. Use undef here if you want to call a library-global
338 function.
339
340 · $function is the name of the function you want to invoke. It can
341 also refer to the name of a constant.
342
343 · @args are the arguments that should be passed to the function. For
344 a method, this should include the invocant. For a constructor,
345 this should include the package name.
346
347 "Glib::Object::Introspection->invoke" returns whatever the function
348 being invoked returns.
349
350 Overrides
351 To override the behavior of a specific function or method, create an
352 appropriately named sub in the correct package and have it call
353 "Glib::Object::Introspection->invoke". Say you want to override
354 "Gtk3::Window::list_toplevels", then do this:
355
356 sub Gtk3::Window::list_toplevels {
357 # ...do something...
358 my $ref = Glib::Object::Introspection->invoke (
359 'Gtk', 'Window', 'list_toplevels',
360 @_);
361 # ...do something...
362 return wantarray ? @$ref : $ref->[$#$ref];
363 }
364
365 The sub's name and package must be those after name corrections.
366
367 Converting a Perl variable to a GValue
368 If you need to marshal into a GValue, then Glib::Object::Introspection
369 cannot do this automatically because the type information is missing.
370 If you do have this information in your module, however, you can use
371 Glib::Object::Introspection::GValueWrapper to do the conversion. In
372 the wrapper for a function that expects a GValue, do this:
373
374 ...
375 my $type = ...; # somehow get the package name that
376 # corresponds to the correct GType
377 my $wrapper =
378 Glib::Object::Introspection::GValueWrapper->new ($type, $value);
379 # now use Glib::Object::Introspection->invoke and
380 # substitute $wrapper where you'd use $value
381 ...
382
383 If you need to call a function that expects an already set-up GValue
384 and modifies it, use "get_value" on the wrapper afterwards to obtain
385 the value. For example:
386
387 my $wrapper =
388 Glib::Object::Introspection::GValueWrapper->new ('Glib::Boolean', 0);
389 $box->child_get_property ($label, 'expand', $gvalue);
390 my $value = $gvalue->get_value
391
392 Handling raw enumerations and flags
393 If you need to handle raw enumerations/flags or extendable enumerations
394 for which more than the pre-defined values might be valid, then use
395 "Glib::Object::Introspection->convert_enum_to_sv",
396 "Glib::Object::Introspection->convert_sv_to_enum",
397 "Glib::Object::Introspection->convert_flags_to_sv" and
398 "Glib::Object::Introspection->convert_sv_to_flags". They will raise an
399 exception on unknown values; catching it then allows you to implement
400 fallback behavior.
401
402 Glib::Object::Introspection->convert_enum_to_sv (package, enum_value)
403 Glib::Object::Introspection->convert_sv_to_enum (package, sv)
404
405 Glib::Object::Introspection->convert_flags_to_sv (package, flags_value)
406 Glib::Object::Introspection->convert_sv_to_flags (package, sv)
407
409 perl-Glib: Glib
410 gobject-introspection: <http://live.gnome.org/GObjectIntrospection>
411 libffi: <http://sourceware.org/libffi/>
412
414 Emmanuele Bassi <ebassi at linux intel com>
415 muppet <scott asofyet org>
416 Torsten Schönfeld <kaffeetisch at gmx de>
417
419 This library is free software; you can redistribute it and/or modify it
420 under the terms of the Lesser General Public License (LGPL). For more
421 information, see http://www.fsf.org/licenses/lgpl.txt
422
423
424
425perl v5.28.0 2018-05-22 Glib::Object::Introspection(3)