What does g_signal_connect_swapped() do?
Asked Answered
Y

1

29

According to GObject reference

g_signal_connect_swapped(instance, detailed_signal, c_handler, data); connects a GCallback function to a signal for a particular object. The instance on which the signal is emitted and data will be swapped when calling the handler.

I don't quite get what this means. Does this mean that the data will point to the object pointed to byinstance and instance will point to the object that was pointed to by data or am I making a mistake here?

If former is the case then what is the logic behind this?

Ylla answered 31/1, 2010 at 12:57 Comment(0)
L
47

You understand correctly.

This allows you to do tricks like the following: You have a button (let's call it button), that is supposed to hide another widget (let's call it textview) when pressed.

You can then do

g_signal_connect_swapped(button, 'clicked', G_CALLBACK(gtk_widget_hide), textview);

to achieve that. When the button is pressed, it generates the 'clicked' signal, and the callback is called with textview as the first argument, and button as the second. In this case the callback is gtk_widget_hide() which only takes one argument, so the second argument is ignored, because that's the way the C calling convention works.

It's the same as the following, but shorter.

static void
on_button_clicked(GtkButton *button, GtkWidget *textview)
{
    gtk_widget_hide(textview);
}

...elsewhere...

    g_signal_connect(button, 'clicked', G_CALLBACK(on_button_clicked), textview);

Basically it saves you from having to write an extra function if you hand-code your interface. Of course, there may be some far more practical use that I've never understood.

Lustful answered 31/1, 2010 at 23:37 Comment(1)
It's also good for generally making events from children invoke handlers with self as the first argument, e.g.: g_signal_connect_swapped (self->some_internal_child, "button-press-event", (GCallback)my_mouse_handler, self). Doing that without swapped would mean having an ugly signature on the receiving side with a 1st argument that probably isn't interesting in the majority of cases, and which you can often get from self-> anyway. Or at least that's how I've made use of this so far...Sympathy

© 2022 - 2024 — McMap. All rights reserved.