GObject 参考手册:教程:如何创建和使用信号

Simple use of signals

The most basic use of signals is to implement simple event notification: for example, if we have a MamanFile object, and if this object has a write method, we might wish to be notified whenever someone uses this method. The code below shows how the user can connect a callback to the write signal. Full code for this simple example is located in sample/signal/maman-file.{h|c} and in sample/signal/test.c

file = g_object_new (MAMAN_FILE_TYPE, NULL);
 
g_signal_connect (G_OBJECT (file), "write",
                  (GCallback)write_event,
                  NULL);
 
maman_file_write (file, buffer, 50);

The MamanFile signal is registered in the class_init function:

klass->write_signal_id = 
  g_signal_newv ("write",
                 G_TYPE_FROM_CLASS (g_class),
                 G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
                 NULL /* class closure */,
                 NULL /* accumulator */,
                 NULL /* accu_data */,
                 g_cclosure_marshal_VOID__VOID,
                 G_TYPE_NONE /* return_type */,
                 0     /* n_params */,
                 NULL  /* param_types */);

and the signal is emitted in maman_file_write:

void maman_file_write (MamanFile *self, guint8 *buffer, guint32 size)
{
  /* First write data. */
  /* Then, notify user of data written. */
  g_signal_emit (self, MAMAN_FILE_GET_CLASS (self)->write_signal_id,
                 0 /* details */, 
                 NULL);
}

As shown above, you can safely set the details parameter to zero if you do not know what it can be used for. For a discussion of what you could used it for, see the section called “The detail argument”

The signature of the signal handler in the above example is defined as g_cclosure_marshal_VOID__VOID. Its name follows a simple convention which encodes the function parameter and return value types in the function name. Specifically, the value in front of the double underscore is the type of the return value, while the value(s) after the double underscore denote the parameter types. The header gobject/gmarshal.h defines a set of commonly needed closures that one can use.

How to provide more flexibility to users?

The previous implementation does the job but the signal facility of GObject can be used to provide even more flexibility to this file change notification mechanism. One of the key ideas is to make the process of writing data to the file part of the signal emission process to allow users to be notified either before or after the data is written to the file.

To integrate the process of writing the data to the file into the signal emission mechanism, we can register a default class closure for this signal which will be invoked during the signal emission, just like any other user-connected signal handler.

The first step to implement this idea is to change the signature of the signal: we need to pass around the buffer to write and its size. To do this, we use our own marshaller which will be generated through GLib’s genmarshall tool. We thus create a file named marshall.list which contains the following single line:

VOID:POINTER,UINT

and use the Makefile provided in sample/signal/Makefile to generate the file named maman-file-complex-marshall.c. This C file is finally included in maman-file-complex.c.

Once the marshaller is present, we register the signal and its marshaller in the class_init function of the object MamanFileComplex (full source for this object is included in sample/signal/maman-file-complex.{h|c}):

GClosure *default_closure;
GType param_types[2];
 
default_closure = g_cclosure_new (G_CALLBACK (default_write_signal_handler),
                                  (gpointer)0xdeadbeaf /* user_data */, 
                                  NULL /* destroy_data */);
 
param_types[0] = G_TYPE_POINTER;
param_types[1] = G_TYPE_UINT;
klass->write_signal_id = 
  g_signal_newv ("write",
                 G_TYPE_FROM_CLASS (g_class),
                 G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
                 default_closure /* class closure */,
                 NULL /* accumulator */,
                 NULL /* accu_data */,
                 maman_file_complex_VOID__POINTER_UINT,
                 G_TYPE_NONE /* return_type */,
                 2     /* n_params */,
                 param_types /* param_types */);

The code shown above first creates the closure which contains the code to complete the file write. This closure is registered as the default class_closure of the newly created signal.

Of course, you need to implement completely the code for the default closure since I just provided a skeleton:

static void
default_write_signal_handler (GObject *obj, guint8 *buffer, guint size, gpointer user_data)
{
  g_assert (user_data == (gpointer)0xdeadbeaf);
  /* Here, we trigger the real file write. */
  g_print ("default signal handler: 0x%x %u\n", buffer, size);
}

Finally, the client code must invoke the maman_file_complex_write function which triggers the signal emission:

void maman_file_complex_write (MamanFileComplex *self, guint8 *buffer, guint size)
{
  /* trigger event */
  g_signal_emit (self,
                 MAMAN_FILE_COMPLEX_GET_CLASS (self)->write_signal_id,
                 0, /* details */
                 buffer, size);
}

The client code (as shown in sample/signal/test.c and below) can now connect signal handlers before and after the file write is completed: since the default signal handler which does the write itself runs during the RUN_LAST phase of the signal emission, it will run after all handlers connected with g_signal_connect and before all handlers connected with g_signal_connect_after. If you intent to write a GObject which emits signals, I would thus urge you to create all your signals with the G_SIGNAL_RUN_LAST such that your users have a maximum of flexibility as to when to get the event. Here, we combined it with G_SIGNAL_NO_RECURSE and G_SIGNAL_NO_HOOKS to ensure our users will not try to do really weird things with our GObject. I strongly advise you to do the same unless you really know why (in which case you really know the inner workings of GSignal by heart and you are not reading this).

static void complex_write_event_before (GObject *file, guint8 *buffer, guint size, gpointer user_data)
{
  g_assert (user_data == NULL);
  g_print ("Complex Write event before: 0x%x, %u\n", buffer, size);
}
 
static void complex_write_event_after (GObject *file, guint8 *buffer, guint size, gpointer user_data)
{
  g_assert (user_data == NULL);
  g_print ("Complex Write event after: 0x%x, %u\n", buffer, size);
}
 
static void test_file_complex (void)
{
  guint8 buffer[100];
  GObject *file;
 
  file = g_object_new (MAMAN_FILE_COMPLEX_TYPE, NULL);
 
  g_signal_connect (G_OBJECT (file), "write",
                    (GCallback)complex_write_event_before,
                    NULL);
 
  g_signal_connect_after (G_OBJECT (file), "write",
                          (GCallback)complex_write_event_after,
                          NULL);
 
  maman_file_complex_write (MAMAN_FILE_COMPLEX (file), buffer, 50);
 
  g_object_unref (G_OBJECT (file));
}

The code above generates the following output on my machine:

Complex Write event before: 0xbfffe280, 50
default signal handler: 0xbfffe280 50
Complex Write event after: 0xbfffe280, 50

How most people do the same thing with less code

For many historic reasons related to how the ancestor of GObject used to work in GTK+ 1.x versions, there is a much simpler [17] way to create a signal with a default handler than to create a closure by hand and to use the g_signal_newv.

For example, g_signal_new can be used to create a signal which uses a default handler which is stored in the class structure of the object. More specifically, the class structure contains a function pointer which is accessed during signal emission to invoke the default handler and the user is expected to provide to g_signal_new the offset from the start of the class structure to the function pointer. [18]

The following code shows the declaration of the MamanFileSimple class structure which contains the write function pointer.

struct _MamanFileSimpleClass {
  GObjectClass parent;
 
  guint write_signal_id;
 
  /* signal default handlers */
  void (*write) (MamanFileSimple *self, guint8 *buffer, guint size);
};

The write function pointer is initialized in the class_init function of the object to default_write_signal_handler:

static void
maman_file_simple_class_init (gpointer g_class,
                               gpointer g_class_data)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (g_class);
  MamanFileSimpleClass *klass = MAMAN_FILE_SIMPLE_CLASS (g_class);
 
  klass->write = default_write_signal_handler;

Finally, the signal is created with g_signal_new in the same class_init function:

klass->write_signal_id = 
 g_signal_new ("write",
               G_TYPE_FROM_CLASS (g_class),
               G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
               G_STRUCT_OFFSET (MamanFileSimpleClass, write),
               NULL /* accumulator */,
               NULL /* accu_data */,
               maman_file_complex_VOID__POINTER_UINT,
               G_TYPE_NONE /* return_type */,
               2     /* n_params */,
               G_TYPE_POINTER,
               G_TYPE_UINT);

Of note, here, is the 4th argument to the function: it is an integer calculated by the G_STRUCT_OFFSET macro which indicates the offset of the member write from the start of the MamanFileSimpleClass class structure. [19]

While the complete code for this type of default handler looks less cluttered as shown in sample/signal/maman-file-simple.{h|c}, it contains numerous subtleties. The main subtle point which everyone must be aware of is that the signature of the default handler created that way does not have a user_data argument: default_write_signal_handler is different in sample/signal/maman-file-complex.c and in sample/signal/maman-file-simple.c.

If you have doubts about which method to use, I would advise you to use the second one which involves g_signal_new rather than g_signal_newv: it is better to write code which looks like the vast majority of other GTK+/GObject code than to do it your own way. However, now, you know why.

How users can abuse signals (and why some think it is good)

Now that you know how to create signals to which the users can connect easily and at any point in the signal emission process thanks to g_signal_connect, g_signal_connect_after and G_SIGNAL_RUN_LAST, it is time to look into how your users can and will screw you. This is also interesting to know how you too, can screw other people. This will make you feel good and eleet.

The users can:

  • stop the emission of the signal at anytime
  • override the default handler of the signal if it is stored as a function pointer in the class structure (which is the preferred way to create a default signal handler, as discussed in the previous section).

In both cases, the original programmer should be as careful as possible to write code which is resistant to the fact that the default handler of the signal might not able to run. This is obviously not the case in the example used in the previous sections since the write to the file depends on whether or not the default handler runs (however, this might be your goal: to allow the user to prevent the file write if he wishes to).

If all you want to do is to stop the signal emission from one of the callbacks you connected yourself, you can call g_signal_stop_by_name. Its use is very simple which is why I won’t detail it further.

If the signal’s default handler is just a class function pointer, it is also possible to override it yourself from the class_init function of a type which derives from the parent. That way, when the signal is emitted, the parent class will use the function provided by the child as a signal default handler. Of course, it is also possible (and recommended) to chain up from the child to the parent’s default signal handler to ensure the integrity of the parent object.

Overriding a class method and chaining up was demonstrated in the section called “Object methods” which is why I won’t bother to show exactly how to do it here again.

Leave a Reply

Your email address will not be published. Required fields are marked *