1 <?xml version="1.0" standalone="no"?>
2 <!DOCTYPE article PUBLIC "-//OASIS//DTD DocBook XML V4.4//EN"
3 "http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd"
9 <title>D-Bus Tutorial</title>
10 <releaseinfo>Version 0.5.0</releaseinfo>
11 <date>20 August 2006</date>
14 <firstname>Havoc</firstname>
15 <surname>Pennington</surname>
17 <orgname>Red Hat, Inc.</orgname>
18 <address><email>hp@pobox.com</email></address>
22 <firstname>David</firstname>
23 <surname>Wheeler</surname>
26 <firstname>John</firstname>
27 <surname>Palmieri</surname>
29 <orgname>Red Hat, Inc.</orgname>
30 <address><email>johnp@redhat.com</email></address>
34 <firstname>Colin</firstname>
35 <surname>Walters</surname>
37 <orgname>Red Hat, Inc.</orgname>
38 <address><email>walters@redhat.com</email></address>
45 <title>Tutorial Work In Progress</title>
48 This tutorial is not complete; it probably contains some useful information, but
49 also has plenty of gaps. Right now, you'll also need to refer to the D-Bus specification,
50 Doxygen reference documentation, and look at some examples of how other apps use D-Bus.
54 Enhancing the tutorial is definitely encouraged - send your patches or suggestions to the
55 mailing list. If you create a D-Bus binding, please add a section to the tutorial for your
56 binding, if only a short section with a couple of examples.
62 <title>What is D-Bus?</title>
64 D-Bus is a system for <firstterm>interprocess communication</firstterm>
65 (IPC). Architecturally, it has several layers:
70 A library, <firstterm>libdbus</firstterm>, that allows two
71 applications to connect to each other and exchange messages.
76 A <firstterm>message bus daemon</firstterm> executable, built on
77 libdbus, that multiple applications can connect to. The daemon can
78 route messages from one application to zero or more other
84 <firstterm>Wrapper libraries</firstterm> or <firstterm>bindings</firstterm>
85 based on particular application frameworks. For example, libdbus-glib and
86 libdbus-qt. There are also bindings to languages such as
87 Python. These wrapper libraries are the API most people should use,
88 as they simplify the details of D-Bus programming. libdbus is
89 intended to be a low-level backend for the higher level bindings.
90 Much of the libdbus API is only useful for binding implementation.
97 libdbus only supports one-to-one connections, just like a raw network
98 socket. However, rather than sending byte streams over the connection, you
99 send <firstterm>messages</firstterm>. Messages have a header identifying
100 the kind of message, and a body containing a data payload. libdbus also
101 abstracts the exact transport used (sockets vs. whatever else), and
102 handles details such as authentication.
106 The message bus daemon forms the hub of a wheel. Each spoke of the wheel
107 is a one-to-one connection to an application using libdbus. An
108 application sends a message to the bus daemon over its spoke, and the bus
109 daemon forwards the message to other connected applications as
110 appropriate. Think of the daemon as a router.
114 The bus daemon has multiple instances on a typical computer. The
115 first instance is a machine-global singleton, that is, a system daemon
116 similar to sendmail or Apache. This instance has heavy security
117 restrictions on what messages it will accept, and is used for systemwide
118 communication. The other instances are created one per user login session.
119 These instances allow applications in the user's session to communicate
124 The systemwide and per-user daemons are separate. Normal within-session
125 IPC does not involve the systemwide message bus process and vice versa.
129 <title>D-Bus applications</title>
131 There are many, many technologies in the world that have "Inter-process
132 communication" or "networking" in their stated purpose: <ulink
133 url="http://www.omg.org">CORBA</ulink>, <ulink
134 url="http://www.opengroup.org/dce/">DCE</ulink>, <ulink
135 url="http://www.microsoft.com/com/">DCOM</ulink>, <ulink
136 url="http://developer.kde.org/documentation/library/kdeqt/dcop.html">DCOP</ulink>, <ulink
137 url="http://www.xmlrpc.com">XML-RPC</ulink>, <ulink
138 url="http://www.w3.org/TR/SOAP/">SOAP</ulink>, <ulink
139 url="http://www.mbus.org/">MBUS</ulink>, <ulink
140 url="http://www.zeroc.com/ice.html">Internet Communications Engine (ICE)</ulink>,
141 and probably hundreds more.
142 Each of these is tailored for particular kinds of application.
143 D-Bus is designed for two specific cases:
147 Communication between desktop applications in the same desktop
148 session; to allow integration of the desktop session as a whole,
149 and address issues of process lifecycle (when do desktop components
150 start and stop running).
155 Communication between the desktop session and the operating system,
156 where the operating system would typically include the kernel
157 and any system daemons or processes.
163 For the within-desktop-session use case, the GNOME and KDE desktops
164 have significant previous experience with different IPC solutions
165 such as CORBA and DCOP. D-Bus is built on that experience and
166 carefully tailored to meet the needs of these desktop projects
167 in particular. D-Bus may or may not be appropriate for other
168 applications; the FAQ has some comparisons to other IPC systems.
171 The problem solved by the systemwide or communication-with-the-OS case
172 is explained well by the following text from the Linux Hotplug project:
175 A gap in current Linux support is that policies with any sort of
176 dynamic "interact with user" component aren't currently
177 supported. For example, that's often needed the first time a network
178 adapter or printer is connected, and to determine appropriate places
179 to mount disk drives. It would seem that such actions could be
180 supported for any case where a responsible human can be identified:
181 single user workstations, or any system which is remotely
186 This is a classic "remote sysadmin" problem, where in this case
187 hotplugging needs to deliver an event from one security domain
188 (operating system kernel, in this case) to another (desktop for
189 logged-in user, or remote sysadmin). Any effective response must go
190 the other way: the remote domain taking some action that lets the
191 kernel expose the desired device capabilities. (The action can often
192 be taken asynchronously, for example letting new hardware be idle
193 until a meeting finishes.) At this writing, Linux doesn't have
194 widely adopted solutions to such problems. However, the new D-Bus
195 work may begin to solve that problem.
200 D-Bus may happen to be useful for purposes other than the one it was
201 designed for. Its general properties that distinguish it from
202 other forms of IPC are:
206 Binary protocol designed to be used asynchronously
207 (similar in spirit to the X Window System protocol).
212 Stateful, reliable connections held open over time.
217 The message bus is a daemon, not a "swarm" or
218 distributed architecture.
223 Many implementation and deployment issues are specified rather
224 than left ambiguous/configurable/pluggable.
229 Semantics are similar to the existing DCOP system, allowing
230 KDE to adopt it more easily.
235 Security features to support the systemwide mode of the
243 <sect1 id="concepts">
244 <title>Concepts</title>
246 Some basic concepts apply no matter what application framework you're
247 using to write a D-Bus application. The exact code you write will be
248 different for GLib vs. Qt vs. Python applications, however.
252 Here is a diagram (<ulink url="diagram.png">png</ulink> <ulink
253 url="diagram.svg">svg</ulink>) that may help you visualize the concepts
258 <title>Native Objects and Object Paths</title>
260 Your programming framework probably defines what an "object" is like;
261 usually with a base class. For example: java.lang.Object, GObject, QObject,
262 python's base Object, or whatever. Let's call this a <firstterm>native object</firstterm>.
265 The low-level D-Bus protocol, and corresponding libdbus API, does not care about native objects.
266 However, it provides a concept called an
267 <firstterm>object path</firstterm>. The idea of an object path is that
268 higher-level bindings can name native object instances, and allow remote applications
273 looks like a filesystem path, for example an object could be
274 named <literal>/org/kde/kspread/sheets/3/cells/4/5</literal>.
275 Human-readable paths are nice, but you are free to create an
276 object named <literal>/com/mycompany/c5yo817y0c1y1c5b</literal>
277 if it makes sense for your application.
280 Namespacing object paths is smart, by starting them with the components
281 of a domain name you own (e.g. <literal>/org/kde</literal>). This
282 keeps different code modules in the same process from stepping
283 on one another's toes.
288 <title>Methods and Signals</title>
291 Each object has <firstterm>members</firstterm>; the two kinds of member
292 are <firstterm>methods</firstterm> and
293 <firstterm>signals</firstterm>. Methods are operations that can be
294 invoked on an object, with optional input (aka arguments or "in
295 parameters") and output (aka return values or "out parameters").
296 Signals are broadcasts from the object to any interested observers
297 of the object; signals may contain a data payload.
301 Both methods and signals are referred to by name, such as
302 "Frobate" or "OnClicked".
307 <sect2 id="interfaces">
308 <title>Interfaces</title>
310 Each object supports one or more <firstterm>interfaces</firstterm>.
311 Think of an interface as a named group of methods and signals,
312 just as it is in GLib or Qt or Java. Interfaces define the
313 <emphasis>type</emphasis> of an object instance.
316 DBus identifies interfaces with a simple namespaced string,
317 something like <literal>org.freedesktop.Introspectable</literal>.
318 Most bindings will map these interface names directly to
319 the appropriate programming language construct, for example
320 to Java interfaces or C++ pure virtual classes.
325 <title>Proxies</title>
327 A <firstterm>proxy object</firstterm> is a convenient native object created to
328 represent a remote object in another process. The low-level DBus API involves manually creating
329 a method call message, sending it, then manually receiving and processing
330 the method reply message. Higher-level bindings provide proxies as an alternative.
331 Proxies look like a normal native object; but when you invoke a method on the proxy
332 object, the binding converts it into a DBus method call message, waits for the reply
333 message, unpacks the return value, and returns it from the native method..
336 In pseudocode, programming without proxies might look like this:
338 Message message = new Message("/remote/object/path", "MethodName", arg1, arg2);
339 Connection connection = getBusConnection();
340 connection.send(message);
341 Message reply = connection.waitForReply(message);
342 if (reply.isError()) {
345 Object returnValue = reply.getReturnValue();
350 Programming with proxies might look like this:
352 Proxy proxy = new Proxy(getBusConnection(), "/remote/object/path");
353 Object returnValue = proxy.MethodName(arg1, arg2);
358 <sect2 id="bus-names">
359 <title>Bus Names</title>
362 When each application connects to the bus daemon, the daemon immediately
363 assigns it a name, called the <firstterm>unique connection name</firstterm>.
364 A unique name begins with a ':' (colon) character. These names are never
365 reused during the lifetime of the bus daemon - that is, you know
366 a given name will always refer to the same application.
367 An example of a unique name might be
368 <literal>:34-907</literal>. The numbers after the colon have
369 no meaning other than their uniqueness.
373 When a name is mapped
374 to a particular application's connection, that application is said to
375 <firstterm>own</firstterm> that name.
379 Applications may ask to own additional <firstterm>well-known
380 names</firstterm>. For example, you could write a specification to
381 define a name called <literal>com.mycompany.TextEditor</literal>.
382 Your definition could specify that to own this name, an application
383 should have an object at the path
384 <literal>/com/mycompany/TextFileManager</literal> supporting the
385 interface <literal>org.freedesktop.FileHandler</literal>.
389 Applications could then send messages to this bus name,
390 object, and interface to execute method calls.
394 You could think of the unique names as IP addresses, and the
395 well-known names as domain names. So
396 <literal>com.mycompany.TextEditor</literal> might map to something like
397 <literal>:34-907</literal> just as <literal>mycompany.com</literal> maps
398 to something like <literal>192.168.0.5</literal>.
402 Names have a second important use, other than routing messages. They
403 are used to track lifecycle. When an application exits (or crashes), its
404 connection to the message bus will be closed by the operating system
405 kernel. The message bus then sends out notification messages telling
406 remaining applications that the application's names have lost their
407 owner. By tracking these notifications, your application can reliably
408 monitor the lifetime of other applications.
412 Bus names can also be used to coordinate single-instance applications.
413 If you want to be sure only one
414 <literal>com.mycompany.TextEditor</literal> application is running for
415 example, have the text editor application exit if the bus name already
421 <sect2 id="addresses">
422 <title>Addresses</title>
425 Applications using D-Bus are either servers or clients. A server
426 listens for incoming connections; a client connects to a server. Once
427 the connection is established, it is a symmetric flow of messages; the
428 client-server distinction only matters when setting up the
433 If you're using the bus daemon, as you probably are, your application
434 will be a client of the bus daemon. That is, the bus daemon listens
435 for connections and your application initiates a connection to the bus
440 A D-Bus <firstterm>address</firstterm> specifies where a server will
441 listen, and where a client will connect. For example, the address
442 <literal>unix:path=/tmp/abcdef</literal> specifies that the server will
443 listen on a UNIX domain socket at the path
444 <literal>/tmp/abcdef</literal> and the client will connect to that
445 socket. An address can also specify TCP/IP sockets, or any other
446 transport defined in future iterations of the D-Bus specification.
450 When using D-Bus with a message bus daemon,
451 libdbus automatically discovers the address of the per-session bus
452 daemon by reading an environment variable. It discovers the
453 systemwide bus daemon by checking a well-known UNIX domain socket path
454 (though you can override this address with an environment variable).
458 If you're using D-Bus without a bus daemon, it's up to you to
459 define which application will be the server and which will be
460 the client, and specify a mechanism for them to agree on
461 the server's address. This is an unusual case.
466 <sect2 id="bigpicture">
467 <title>Big Conceptual Picture</title>
470 Pulling all these concepts together, to specify a particular
471 method call on a particular object instance, a number of
472 nested components have to be named:
474 Address -> [Bus Name] -> Path -> Interface -> Method
476 The bus name is in brackets to indicate that it's optional -- you only
477 provide a name to route the method call to the right application
478 when using the bus daemon. If you have a direct connection to another
479 application, bus names aren't used; there's no bus daemon.
483 The interface is also optional, primarily for historical
484 reasons; DCOP does not require specifying the interface,
485 instead simply forbidding duplicate method names
486 on the same object instance. D-Bus will thus let you
487 omit the interface, but if your method name is ambiguous
488 it is undefined which method will be invoked.
493 <sect2 id="messages">
494 <title>Messages - Behind the Scenes</title>
496 D-Bus works by sending messages between processes. If you're using
497 a sufficiently high-level binding, you may never work with messages directly.
500 There are 4 message types:
504 Method call messages ask to invoke a method
510 Method return messages return the results
511 of invoking a method.
516 Error messages return an exception caused by
522 Signal messages are notifications that a given signal
523 has been emitted (that an event has occurred).
524 You could also think of these as "event" messages.
530 A method call maps very simply to messages: you send a method call
531 message, and receive either a method return message or an error message
535 Each message has a <firstterm>header</firstterm>, including <firstterm>fields</firstterm>,
536 and a <firstterm>body</firstterm>, including <firstterm>arguments</firstterm>. You can think
537 of the header as the routing information for the message, and the body as the payload.
538 Header fields might include the sender bus name, destination bus name, method or signal name,
539 and so forth. One of the header fields is a <firstterm>type signature</firstterm> describing the
540 values found in the body. For example, the letter "i" means "32-bit integer" so the signature
541 "ii" means the payload has two 32-bit integers.
545 <sect2 id="callprocedure">
546 <title>Calling a Method - Behind the Scenes</title>
549 A method call in DBus consists of two messages; a method call message sent from process A to process B,
550 and a matching method reply message sent from process B to process A. Both the call and the reply messages
551 are routed through the bus daemon. The caller includes a different serial number in each call message, and the
552 reply message includes this number to allow the caller to match replies to calls.
556 The call message will contain any arguments to the method.
557 The reply message may indicate an error, or may contain data returned by the method.
561 A method invocation in DBus happens as follows:
565 The language binding may provide a proxy, such that invoking a method on
566 an in-process object invokes a method on a remote object in another process. If so, the
567 application calls a method on the proxy, and the proxy
568 constructs a method call message to send to the remote process.
573 For more low-level APIs, the application may construct a method call message itself, without
579 In either case, the method call message contains: a bus name belonging to the remote process; the name of the method;
580 the arguments to the method; an object path inside the remote process; and optionally the name of the
581 interface that specifies the method.
586 The method call message is sent to the bus daemon.
591 The bus daemon looks at the destination bus name. If a process owns that name,
592 the bus daemon forwards the method call to that process. Otherwise, the bus daemon
593 creates an error message and sends it back as the reply to the method call message.
598 The receiving process unpacks the method call message. In a simple low-level API situation, it
599 may immediately run the method and send a method reply message to the bus daemon.
600 When using a high-level binding API, the binding might examine the object path, interface,
601 and method name, and convert the method call message into an invocation of a method on
602 a native object (GObject, java.lang.Object, QObject, etc.), then convert the return
603 value from the native method into a method reply message.
608 The bus daemon receives the method reply message and sends it to the process that
609 made the method call.
614 The process that made the method call looks at the method reply and makes use of any
615 return values included in the reply. The reply may also indicate that an error occurred.
616 When using a binding, the method reply message may be converted into the return value of
617 of a proxy method, or into an exception.
624 The bus daemon never reorders messages. That is, if you send two method call messages to the same recipient,
625 they will be received in the order they were sent. The recipient is not required to reply to the calls
626 in order, however; for example, it may process each method call in a separate thread, and return reply messages
627 in an undefined order depending on when the threads complete. Method calls have a unique serial
628 number used by the method caller to match reply messages to call messages.
633 <sect2 id="signalprocedure">
634 <title>Emitting a Signal - Behind the Scenes</title>
637 A signal in DBus consists of a single message, sent by one process to any number of other processes.
638 That is, a signal is a unidirectional broadcast. The signal may contain arguments (a data payload), but
639 because it is a broadcast, it never has a "return value." Contrast this with a method call
640 (see <xref linkend="callprocedure"/>) where the method call message has a matching method reply message.
644 The emitter (aka sender) of a signal has no knowledge of the signal recipients. Recipients register
645 with the bus daemon to receive signals based on "match rules" - these rules would typically include the sender and
646 the signal name. The bus daemon sends each signal only to recipients who have expressed interest in that
651 A signal in DBus happens as follows:
655 A signal message is created and sent to the bus daemon. When using the low-level API this may be
656 done manually, with certain bindings it may be done for you by the binding when a native object
657 emits a native signal or event.
662 The signal message contains the name of the interface that specifies the signal;
663 the name of the signal; the bus name of the process sending the signal; and
669 Any process on the message bus can register "match rules" indicating which signals it
670 is interested in. The bus has a list of registered match rules.
675 The bus daemon examines the signal and determines which processes are interested in it.
676 It sends the signal message to these processes.
681 Each process receiving the signal decides what to do with it; if using a binding,
682 the binding may choose to emit a native signal on a proxy object. If using the
683 low-level API, the process may just look at the signal sender and name and decide
684 what to do based on that.
692 <sect2 id="introspection">
693 <title>Introspection</title>
696 D-Bus objects may support the interface <literal>org.freedesktop.DBus.Introspectable</literal>.
697 This interface has one method <literal>Introspect</literal> which takes no arguments and returns
698 an XML string. The XML string describes the interfaces, methods, and signals of the object.
699 See the D-Bus specification for more details on this introspection format.
706 <sect1 id="glib-client">
707 <title>GLib API: Using Remote Objects</title>
710 The GLib binding is defined in the header file
711 <literal><dbus/dbus-glib.h></literal>.
714 <sect2 id="glib-typemappings">
715 <title>D-Bus - GLib type mappings</title>
717 The heart of the GLib bindings for D-Bus is the mapping it
718 provides between D-Bus "type signatures" and GLib types
719 (<literal>GType</literal>). The D-Bus type system is composed of
720 a number of "basic" types, along with several "container" types.
722 <sect3 id="glib-basic-typemappings">
723 <title>Basic type mappings</title>
725 Below is a list of the basic types, along with their associated
726 mapping to a <literal>GType</literal>.
731 <entry>D-Bus basic type</entry>
733 <entry>Free function</entry>
739 <entry><literal>BYTE</literal></entry>
740 <entry><literal>G_TYPE_UCHAR</literal></entry>
744 <entry><literal>BOOLEAN</literal></entry>
745 <entry><literal>G_TYPE_BOOLEAN</literal></entry>
749 <entry><literal>INT16</literal></entry>
750 <entry><literal>G_TYPE_INT</literal></entry>
752 <entry>Will be changed to a <literal>G_TYPE_INT16</literal> once GLib has it</entry>
754 <entry><literal>UINT16</literal></entry>
755 <entry><literal>G_TYPE_UINT</literal></entry>
757 <entry>Will be changed to a <literal>G_TYPE_UINT16</literal> once GLib has it</entry>
759 <entry><literal>INT32</literal></entry>
760 <entry><literal>G_TYPE_INT</literal></entry>
762 <entry>Will be changed to a <literal>G_TYPE_INT32</literal> once GLib has it</entry>
764 <entry><literal>UINT32</literal></entry>
765 <entry><literal>G_TYPE_UINT</literal></entry>
767 <entry>Will be changed to a <literal>G_TYPE_UINT32</literal> once GLib has it</entry>
769 <entry><literal>INT64</literal></entry>
770 <entry><literal>G_TYPE_GINT64</literal></entry>
774 <entry><literal>UINT64</literal></entry>
775 <entry><literal>G_TYPE_GUINT64</literal></entry>
779 <entry><literal>DOUBLE</literal></entry>
780 <entry><literal>G_TYPE_DOUBLE</literal></entry>
784 <entry><literal>STRING</literal></entry>
785 <entry><literal>G_TYPE_STRING</literal></entry>
786 <entry><literal>g_free</literal></entry>
789 <entry><literal>OBJECT_PATH</literal></entry>
790 <entry><literal>DBUS_TYPE_G_PROXY</literal></entry>
791 <entry><literal>g_object_unref</literal></entry>
792 <entry>The returned proxy does not have an interface set; use <literal>dbus_g_proxy_set_interface</literal> to invoke methods</entry>
797 As you can see, the basic mapping is fairly straightforward.
800 <sect3 id="glib-container-typemappings">
801 <title>Container type mappings</title>
803 The D-Bus type system also has a number of "container"
804 types, such as <literal>DBUS_TYPE_ARRAY</literal> and
805 <literal>DBUS_TYPE_STRUCT</literal>. The D-Bus type system
806 is fully recursive, so one can for example have an array of
807 array of strings (i.e. type signature
808 <literal>aas</literal>).
811 However, not all of these types are in common use; for
812 example, at the time of this writing the author knows of no
813 one using <literal>DBUS_TYPE_STRUCT</literal>, or a
814 <literal>DBUS_TYPE_ARRAY</literal> containing any non-basic
815 type. The approach the GLib bindings take is pragmatic; try
816 to map the most common types in the most obvious way, and
817 let using less common and more complex types be less
821 First, D-Bus type signatures which have an "obvious"
822 corresponding built-in GLib type are mapped using that type:
827 <entry>D-Bus type signature</entry>
828 <entry>Description</entry>
830 <entry>C typedef</entry>
831 <entry>Free function</entry>
837 <entry><literal>as</literal></entry>
838 <entry>Array of strings</entry>
839 <entry><literal>G_TYPE_STRV</literal></entry>
840 <entry><literal>char **</literal></entry>
841 <entry><literal>g_strfreev</literal></entry>
844 <entry><literal>v</literal></entry>
845 <entry>Generic value container</entry>
846 <entry><literal>G_TYPE_VALUE</literal></entry>
847 <entry><literal>GValue *</literal></entry>
848 <entry><literal>g_value_unset</literal></entry>
849 <entry>The calling conventions for values expect that method callers have allocated return values; see below.</entry>
856 The next most common recursive type signatures are arrays of
857 basic values. The most obvious mapping for arrays of basic
858 types is a <literal>GArray</literal>. Now, GLib does not
859 provide a builtin <literal>GType</literal> for
860 <literal>GArray</literal>. However, we actually need more than
861 that - we need a "parameterized" type which includes the
862 contained type. Why we need this we will see below.
865 The approach taken is to create these types in the D-Bus GLib
866 bindings; however, there is nothing D-Bus specific about them.
867 In the future, we hope to include such "fundamental" types in GLib
873 <entry>D-Bus type signature</entry>
874 <entry>Description</entry>
876 <entry>C typedef</entry>
877 <entry>Free function</entry>
883 <entry><literal>ay</literal></entry>
884 <entry>Array of bytes</entry>
885 <entry><literal>DBUS_TYPE_G_BYTE_ARRAY</literal></entry>
886 <entry><literal>GArray *</literal></entry>
887 <entry>g_array_free</entry>
891 <entry><literal>au</literal></entry>
892 <entry>Array of uint</entry>
893 <entry><literal>DBUS_TYPE_G_UINT_ARRAY</literal></entry>
894 <entry><literal>GArray *</literal></entry>
895 <entry>g_array_free</entry>
899 <entry><literal>ai</literal></entry>
900 <entry>Array of int</entry>
901 <entry><literal>DBUS_TYPE_G_INT_ARRAY</literal></entry>
902 <entry><literal>GArray *</literal></entry>
903 <entry>g_array_free</entry>
907 <entry><literal>ax</literal></entry>
908 <entry>Array of int64</entry>
909 <entry><literal>DBUS_TYPE_G_INT64_ARRAY</literal></entry>
910 <entry><literal>GArray *</literal></entry>
911 <entry>g_array_free</entry>
915 <entry><literal>at</literal></entry>
916 <entry>Array of uint64</entry>
917 <entry><literal>DBUS_TYPE_G_UINT64_ARRAY</literal></entry>
918 <entry><literal>GArray *</literal></entry>
919 <entry>g_array_free</entry>
923 <entry><literal>ad</literal></entry>
924 <entry>Array of double</entry>
925 <entry><literal>DBUS_TYPE_G_DOUBLE_ARRAY</literal></entry>
926 <entry><literal>GArray *</literal></entry>
927 <entry>g_array_free</entry>
931 <entry><literal>ab</literal></entry>
932 <entry>Array of boolean</entry>
933 <entry><literal>DBUS_TYPE_G_BOOLEAN_ARRAY</literal></entry>
934 <entry><literal>GArray *</literal></entry>
935 <entry>g_array_free</entry>
943 D-Bus also includes a special type DBUS_TYPE_DICT_ENTRY which
944 is only valid in arrays. It's intended to be mapped to a "dictionary"
945 type by bindings. The obvious GLib mapping here is GHashTable. Again,
946 however, there is no builtin <literal>GType</literal> for a GHashTable.
947 Moreover, just like for arrays, we need a parameterized type so that
948 the bindings can communiate which types are contained in the hash table.
951 At present, only strings are supported. Work is in progress to
957 <entry>D-Bus type signature</entry>
958 <entry>Description</entry>
960 <entry>C typedef</entry>
961 <entry>Free function</entry>
967 <entry><literal>a{ss}</literal></entry>
968 <entry>Dictionary mapping strings to strings</entry>
969 <entry><literal>DBUS_TYPE_G_STRING_STRING_HASHTABLE</literal></entry>
970 <entry><literal>GHashTable *</literal></entry>
971 <entry>g_hash_table_destroy</entry>
979 <sect3 id="glib-generic-typemappings">
980 <title>Arbitrarily recursive type mappings</title>
982 Finally, it is possible users will want to write or invoke D-Bus
983 methods which have arbitrarily complex type signatures not
984 directly supported by these bindings. For this case, we have a
985 <literal>DBusGValue</literal> which acts as a kind of special
986 variant value which may be iterated over manually. The
987 <literal>GType</literal> associated is
988 <literal>DBUS_TYPE_G_VALUE</literal>.
991 TODO insert usage of <literal>DBUS_TYPE_G_VALUE</literal> here.
995 <sect2 id="sample-program-1">
996 <title>A sample program</title>
997 <para>Here is a D-Bus program using the GLib bindings.
1000 main (int argc, char **argv)
1002 DBusGConnection *connection;
1006 char **name_list_ptr;
1011 connection = dbus_g_bus_get (DBUS_BUS_SESSION,
1013 if (connection == NULL)
1015 g_printerr ("Failed to open connection to bus: %s\n",
1017 g_error_free (error);
1021 /* Create a proxy object for the "bus driver" (name "org.freedesktop.DBus") */
1023 proxy = dbus_g_proxy_new_for_name (connection,
1026 DBUS_INTERFACE_DBUS);
1028 /* Call ListNames method, wait for reply */
1030 if (!dbus_g_proxy_call (proxy, "ListNames", &error, G_TYPE_INVALID,
1031 G_TYPE_STRV, &name_list, G_TYPE_INVALID))
1033 /* Just do demonstrate remote exceptions versus regular GError */
1034 if (error->domain == DBUS_GERROR && error->code == DBUS_GERROR_REMOTE_EXCEPTION)
1035 g_printerr ("Caught remote method exception %s: %s",
1036 dbus_g_error_get_name (error),
1039 g_printerr ("Error: %s\n", error->message);
1040 g_error_free (error);
1044 /* Print the results */
1046 g_print ("Names on the message bus:\n");
1048 for (name_list_ptr = name_list; *name_list_ptr; name_list_ptr++)
1050 g_print (" %s\n", *name_list_ptr);
1052 g_strfreev (name_list);
1054 g_object_unref (proxy);
1061 <sect2 id="glib-program-setup">
1062 <title>Program initalization</title>
1064 A connection to the bus is acquired using
1065 <literal>dbus_g_bus_get</literal>. Next, a proxy
1066 is created for the object "/org/freedesktop/DBus" with
1067 interface <literal>org.freedesktop.DBus</literal>
1068 on the service <literal>org.freedesktop.DBus</literal>.
1069 This is a proxy for the message bus itself.
1072 <sect2 id="glib-method-invocation">
1073 <title>Understanding method invocation</title>
1075 You have a number of choices for method invocation. First, as
1076 used above, <literal>dbus_g_proxy_call</literal> sends a
1077 method call to the remote object, and blocks until a reply is
1078 recieved. The outgoing arguments are specified in the varargs
1079 array, terminated with <literal>G_TYPE_INVALID</literal>.
1080 Next, pointers to return values are specified, followed again
1081 by <literal>G_TYPE_INVALID</literal>.
1084 To invoke a method asynchronously, use
1085 <literal>dbus_g_proxy_begin_call</literal>. This returns a
1086 <literal>DBusGPendingCall</literal> object; you may then set a
1087 notification function using
1088 <literal>dbus_g_pending_call_set_notify</literal>.
1091 <sect2 id="glib-signal-connection">
1092 <title>Connecting to object signals</title>
1094 You may connect to signals using
1095 <literal>dbus_g_proxy_add_signal</literal> and
1096 <literal>dbus_g_proxy_connect_signal</literal>. You must
1097 invoke <literal>dbus_g_proxy_add_signal</literal> to specify
1098 the signature of your signal handlers; you may then invoke
1099 <literal>dbus_g_proxy_connect_signal</literal> multiple times.
1102 Note that it will often be the case that there is no builtin
1103 marshaller for the type signature of a remote signal. In that
1104 case, you must generate a marshaller yourself by using
1105 <application>glib-genmarshal</application>, and then register
1106 it using <literal>dbus_g_object_register_marshaller</literal>.
1109 <sect2 id="glib-error-handling">
1110 <title>Error handling and remote exceptions</title>
1112 All of the GLib binding methods such as
1113 <literal>dbus_g_proxy_end_call</literal> return a
1114 <literal>GError</literal>. This <literal>GError</literal> can
1115 represent two different things:
1119 An internal D-Bus error, such as an out-of-memory
1120 condition, an I/O error, or a network timeout. Errors
1121 generated by the D-Bus library itself have the domain
1122 <literal>DBUS_GERROR</literal>, and a corresponding code
1123 such as <literal>DBUS_GERROR_NO_MEMORY</literal>. It will
1124 not be typical for applications to handle these errors
1130 A remote D-Bus exception, thrown by the peer, bus, or
1131 service. D-Bus remote exceptions have both a textual
1132 "name" and a "message". The GLib bindings store this
1133 information in the <literal>GError</literal>, but some
1134 special rules apply.
1137 The set error will have the domain
1138 <literal>DBUS_GERROR</literal> as above, and will also
1140 <literal>DBUS_GERROR_REMOTE_EXCEPTION</literal>. In order
1141 to access the remote exception name, you must use a
1142 special accessor, such as
1143 <literal>dbus_g_error_has_name</literal> or
1144 <literal>dbus_g_error_get_name</literal>. The remote
1145 exception detailed message is accessible via the regular
1146 GError <literal>message</literal> member.
1152 <sect2 id="glib-more-examples">
1153 <title>More examples of method invocation</title>
1154 <sect3 id="glib-sending-stuff">
1155 <title>Sending an integer and string, receiving an array of bytes</title>
1161 if (!dbus_g_proxy_call (proxy, "Foobar", &error,
1162 G_TYPE_INT, 42, G_TYPE_STRING, "hello",
1164 DBUS_TYPE_G_UCHAR_ARRAY, &arr, G_TYPE_INVALID))
1168 g_assert (arr != NULL);
1169 printf ("got back %u values", arr->len);
1173 <sect3 id="glib-sending-hash">
1174 <title>Sending a GHashTable</title>
1177 GHashTable *hash = g_hash_table_new (g_str_hash, g_str_equal);
1180 g_hash_table_insert (hash, "foo", "bar");
1181 g_hash_table_insert (hash, "baz", "whee");
1184 if (!dbus_g_proxy_call (proxy, "HashSize", &error,
1185 DBUS_TYPE_G_STRING_STRING_HASH, hash, G_TYPE_INVALID,
1186 G_TYPE_UINT, &ret, G_TYPE_INVALID))
1190 g_assert (ret == 2);
1191 g_hash_table_destroy (hash);
1195 <sect3 id="glib-receiving-bool-int">
1196 <title>Receiving a boolean and a string</title>
1203 if (!dbus_g_proxy_call (proxy, "GetStuff", &error,
1205 G_TYPE_BOOLEAN, &boolret,
1206 G_TYPE_STRING, &strret,
1211 printf ("%s %s", boolret ? "TRUE" : "FALSE", strret);
1216 <sect3 id="glib-sending-str-arrays">
1217 <title>Sending two arrays of strings</title>
1220 /* NULL terminate */
1221 char *strs_static[] = {"foo", "bar", "baz", NULL};
1222 /* Take pointer to array; cannot pass array directly */
1223 char **strs_static_p = strs_static;
1224 char **strs_dynamic;
1226 strs_dynamic = g_new (char *, 4);
1227 strs_dynamic[0] = g_strdup ("hello");
1228 strs_dynamic[1] = g_strdup ("world");
1229 strs_dynamic[2] = g_strdup ("!");
1230 /* NULL terminate */
1231 strs_dynamic[3] = NULL;
1234 if (!dbus_g_proxy_call (proxy, "TwoStrArrays", &error,
1235 G_TYPE_STRV, strs_static_p,
1236 G_TYPE_STRV, strs_dynamic,
1242 g_strfreev (strs_dynamic);
1246 <sect3 id="glib-getting-str-array">
1247 <title>Sending a boolean, receiving an array of strings</title>
1256 if (!dbus_g_proxy_call (proxy, "GetStrs", &error,
1257 G_TYPE_BOOLEAN, blah,
1259 G_TYPE_STRV, &strs,
1264 for (strs_p = strs; *strs_p; strs_p++)
1265 printf ("got string: \"%s\"", *strs_p);
1270 <sect3 id="glib-sending-variant">
1271 <title>Sending a variant</title>
1276 g_value_init (&val, G_TYPE_STRING);
1277 g_value_set_string (&val, "hello world");
1280 if (!dbus_g_proxy_call (proxy, "SendVariant", &error,
1281 G_TYPE_VALUE, &val, G_TYPE_INVALID,
1286 g_assert (ret == 2);
1287 g_value_unset (&val);
1291 <sect3 id="glib-receiving-variant">
1292 <title>Receiving a variant</title>
1298 if (!dbus_g_proxy_call (proxy, "GetVariant", &error, G_TYPE_INVALID,
1299 G_TYPE_VALUE, &val, G_TYPE_INVALID))
1303 if (G_VALUE_TYPE (&val) == G_TYPE_STRING)
1304 printf ("%s\n", g_value_get_string (&val));
1305 else if (G_VALUE_TYPE (&val) == G_TYPE_INT)
1306 printf ("%d\n", g_value_get_int (&val));
1309 g_value_unset (&val);
1315 <sect2 id="glib-generated-bindings">
1316 <title>Generated Bindings</title>
1318 By using the Introspection XML files, convenient client-side bindings
1319 can be automatically created to ease the use of a remote DBus object.
1322 Here is a sample XML file which describes an object that exposes
1323 one method, named <literal>ManyArgs</literal>.
1325 <?xml version="1.0" encoding="UTF-8" ?>
1326 <node name="/com/example/MyObject">
1327 <interface name="com.example.MyObject">
1328 <method name="ManyArgs">
1329 <arg type="u" name="x" direction="in" />
1330 <arg type="s" name="str" direction="in" />
1331 <arg type="d" name="trouble" direction="in" />
1332 <arg type="d" name="d_ret" direction="out" />
1333 <arg type="s" name="str_ret" direction="out" />
1340 Run <literal>dbus-binding-tool --mode=glib-client
1341 <replaceable>FILENAME</replaceable> >
1342 <replaceable>HEADER_NAME</replaceable></literal> to generate the header
1343 file. For example: <command>dbus-binding-tool --mode=glib-client
1344 my-object.xml > my-object-bindings.h</command>. This will generate
1345 inline functions with the following prototypes:
1347 /* This is a blocking call */
1349 com_example_MyObject_many_args (DBusGProxy *proxy, const guint IN_x,
1350 const char * IN_str, const gdouble IN_trouble,
1351 gdouble* OUT_d_ret, char ** OUT_str_ret,
1354 /* This is a non-blocking call */
1356 com_example_MyObject_many_args_async (DBusGProxy *proxy, const guint IN_x,
1357 const char * IN_str, const gdouble IN_trouble,
1358 com_example_MyObject_many_args_reply callback,
1361 /* This is the typedef for the non-blocking callback */
1363 (*com_example_MyObject_many_args_reply)
1364 (DBusGProxy *proxy, gdouble OUT_d_ret, char * OUT_str_ret,
1365 GError *error, gpointer userdata);
1367 The first argument in all functions is a <literal>DBusGProxy
1368 *</literal>, which you should create with the usual
1369 <literal>dbus_g_proxy_new_*</literal> functions. Following that are the
1370 "in" arguments, and then either the "out" arguments and a
1371 <literal>GError *</literal> for the synchronous (blocking) function, or
1372 callback and user data arguments for the asynchronous (non-blocking)
1373 function. The callback in the asynchronous function passes the
1374 <literal>DBusGProxy *</literal>, the returned "out" arguments, an
1375 <literal>GError *</literal> which is set if there was an error otherwise
1376 <literal>NULL</literal>, and the user data.
1379 As with the server-side bindings support (see <xref
1380 linkend="glib-server"/>), the exact behaviour of the client-side
1381 bindings can be manipulated using "annotations". Currently the only
1382 annotation used by the client bindings is
1383 <literal>org.freedesktop.DBus.GLib.NoReply</literal>, which sets the
1384 flag indicating that the client isn't expecting a reply to the method
1385 call, so a reply shouldn't be sent. This is often used to speed up
1386 rapid method calls where there are no "out" arguments, and not knowing
1387 if the method succeeded is an acceptable compromise to half the traffic
1393 <sect1 id="glib-server">
1394 <title>GLib API: Implementing Objects</title>
1396 At the moment, to expose a GObject via D-Bus, you must
1397 write XML by hand which describes the methods exported
1398 by the object. In the future, this manual step will
1399 be obviated by the upcoming GLib introspection support.
1402 Here is a sample XML file which describes an object that exposes
1403 one method, named <literal>ManyArgs</literal>.
1405 <?xml version="1.0" encoding="UTF-8" ?>
1407 <node name="/com/example/MyObject">
1409 <interface name="com.example.MyObject">
1410 <annotation name="org.freedesktop.DBus.GLib.CSymbol" value="my_object"/>
1411 <method name="ManyArgs">
1412 <!-- This is optional, and in this case is redunundant -->
1413 <annotation name="org.freedesktop.DBus.GLib.CSymbol" value="my_object_many_args"/>
1414 <arg type="u" name="x" direction="in" />
1415 <arg type="s" name="str" direction="in" />
1416 <arg type="d" name="trouble" direction="in" />
1417 <arg type="d" name="d_ret" direction="out" />
1418 <arg type="s" name="str_ret" direction="out" />
1425 This XML is in the same format as the D-Bus introspection XML
1426 format. Except we must include an "annotation" which give the C
1427 symbols corresponding to the object implementation prefix
1428 (<literal>my_object</literal>). In addition, if particular
1429 methods symbol names deviate from C convention
1430 (i.e. <literal>ManyArgs</literal> ->
1431 <literal>many_args</literal>), you may specify an annotation
1432 giving the C symbol.
1435 Once you have written this XML, run <literal>dbus-binding-tool --mode=glib-server <replaceable>FILENAME</replaceable> > <replaceable>HEADER_NAME</replaceable>.</literal> to
1436 generate a header file. For example: <command>dbus-binding-tool --mode=glib-server my-object.xml > my-object-glue.h</command>.
1439 Next, include the generated header in your program, and invoke
1440 <literal>dbus_g_object_class_install_info</literal> in the class
1441 initializer, passing the object class and "object info" included in the
1442 header. For example:
1444 dbus_g_object_type_install_info (COM_FOO_TYPE_MY_OBJECT, &com_foo_my_object_info);
1446 This should be done exactly once per object class.
1449 To actually implement the method, just define a C function named e.g.
1450 <literal>my_object_many_args</literal> in the same file as the info
1451 header is included. At the moment, it is required that this function
1452 conform to the following rules:
1456 The function must return a value of type <literal>gboolean</literal>;
1457 <literal>TRUE</literal> on success, and <literal>FALSE</literal>
1463 The first parameter is a pointer to an instance of the object.
1468 Following the object instance pointer are the method
1474 Following the input values are pointers to return values.
1479 The final parameter must be a <literal>GError **</literal>.
1480 If the function returns <literal>FALSE</literal> for an
1481 error, the error parameter must be initalized with
1482 <literal>g_set_error</literal>.
1488 Finally, you can export an object using <literal>dbus_g_connection_register_g_object</literal>. For example:
1490 dbus_g_connection_register_g_object (connection,
1491 "/com/foo/MyObject",
1496 <sect2 id="glib-annotations">
1497 <title>Server-side Annotations</title>
1499 There are several annotations that are used when generating the
1500 server-side bindings. The most common annotation is
1501 <literal>org.freedesktop.DBus.GLib.CSymbol</literal> but there are other
1502 annotations which are often useful.
1505 <term><literal>org.freedesktop.DBus.GLib.CSymbol</literal></term>
1508 This annotation is used to specify the C symbol names for
1509 the various types (interface, method, etc), if it differs from the
1510 name DBus generates.
1515 <term><literal>org.freedesktop.DBus.GLib.Async</literal></term>
1518 This annotation marks the method implementation as an
1519 asynchronous function, which doesn't return a response straight
1520 away but will send the response at some later point to complete
1521 the call. This is used to implement non-blocking services where
1522 method calls can take time.
1525 When a method is asynchronous, the function prototype is
1526 different. It is required that the function conform to the
1531 The function must return a value of type <literal>gboolean</literal>;
1532 <literal>TRUE</literal> on success, and <literal>FALSE</literal>
1533 otherwise. TODO: the return value is currently ignored.
1538 The first parameter is a pointer to an instance of the object.
1543 Following the object instance pointer are the method
1549 The final parameter must be a
1550 <literal>DBusGMethodInvocation *</literal>. This is used
1551 when sending the response message back to the client, by
1552 calling <literal>dbus_g_method_return</literal> or
1553 <literal>dbus_g_method_return_error</literal>.
1561 <term><literal>org.freedesktop.DBus.GLib.Const</literal></term>
1563 <para>This attribute can only be applied to "out"
1564 <literal><arg></literal> nodes, and specifies that the
1565 parameter isn't being copied when returned. For example, this
1566 turns a 's' argument from a <literal>char **</literal> to a
1567 <literal>const char **</literal>, and results in the argument not
1568 being freed by DBus after the message is sent.
1573 <term><literal>org.freedesktop.DBus.GLib.ReturnVal</literal></term>
1576 This attribute can only be applied to "out"
1577 <literal><arg></literal> nodes, and alters the expected
1578 function signature. It currently can be set to two values:
1579 <literal>""</literal> or <literal>"error"</literal>. The
1580 argument marked with this attribute is not returned via a
1581 pointer argument, but by the function's return value. If the
1582 attribute's value is the empty string, the <literal>GError
1583 *</literal> argument is also omitted so there is no standard way
1584 to return an error value. This is very useful for interfacing
1585 with existing code, as it is possible to match existing APIs.
1586 If the attribute's value is <literal>"error"</literal>, then the
1587 final argument is a <literal>GError *</literal> as usual.
1590 Some examples to demonstrate the usage. This introspection XML:
1592 <method name="Increment">
1593 <arg type="u" name="x" />
1594 <arg type="u" direction="out" />
1597 Expects the following function declaration:
1600 my_object_increment (MyObject *obj, gint32 x, gint32 *ret, GError **error);
1604 This introspection XML:
1606 <method name="IncrementRetval">
1607 <arg type="u" name="x" />
1608 <arg type="u" direction="out" >
1609 <annotation name="org.freedesktop.DBus.GLib.ReturnVal" value=""/>
1613 Expects the following function declaration:
1616 my_object_increment_retval (MyObject *obj, gint32 x)
1620 This introspection XML:
1622 <method name="IncrementRetvalError">
1623 <arg type="u" name="x" />
1624 <arg type="u" direction="out" >
1625 <annotation name="org.freedesktop.DBus.GLib.ReturnVal" value="error"/>
1629 Expects the following function declaration:
1632 my_object_increment_retval_error (MyObject *obj, gint32 x, GError **error)
1642 <sect1 id="python-client">
1643 <title>Python API</title>
1645 The Python API, dbus-python, is now documented separately in
1646 <ulink url="http://dbus.freedesktop.org/doc/dbus-python/doc/tutorial.html">the dbus-python tutorial</ulink> (also available in doc/tutorial.txt,
1647 and doc/tutorial.html if built with python-docutils, in the dbus-python
1648 source distribution).
1652 <sect1 id="qt-client">
1653 <title>Qt API: Using Remote Objects</title>
1656 The Qt bindings are not yet documented.
1661 <sect1 id="qt-server">
1662 <title>Qt API: Implementing Objects</title>
1664 The Qt bindings are not yet documented.