Search code examples
linuxgtkgtk3

gtk 3.0 use the same callback for several switches


I'm creating a Linux GUI using GTK3.0 and C and I want to use the same callback for several switches. In order to differentiate the switch that was clicked, I am trying to use the gpointer argument in g_signal_connect, but the callback doesn't seem to receive the right value.

I create the signals this way:

g_signal_connect(led1_switch, "state-set", G_CALLBACK(on_gpio_btn_click), (gpointer)"LED1");
g_signal_connect(led2_switch, "state-set", G_CALLBACK(on_gpio_btn_click), (gpointer)"LED2");

And the callback tries to get the gpointer passed:

    static void on_gpio_btn_click(GtkWidget *wid, gpointer ptr)
    {
        int gpio;
        int val = 0;
        char *gpio_switch = ptr;
...

But when I debug the application, the ptr pointer has the value 0x1, a wrong memory address. enter image description here

Shouldn't it point to the memory address where the constant string "LED1" is stored? what am I doing wrong? How can I share the same callback for several widgets? I have 8 switches to control GPIOs and I would prefer to have one callback for all of them instead of creating eight.


Solution

  • Your function signature is wrong: the 2nd argument is the value of the switch's state, as can be found in the documentation of the "state-set" signal. That's also the reason why the value is 1: that's the actual value of TRUE.

    In other words, your callback will like this:

        static void on_gpio_btn_click(GtkSwitch *swtch, gboolean state, gpointer ptr)
        {
            int gpio;
            int val = 0;
            char *gpio_switch = ptr;
            // ...
        }