Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing integer as gpointer in g_signal_connect

Tags:

c

gtk3

I tried finding a similar question, but couldn't find any solutions.

I have a piece of software written in C using GTK3, and I'm trying to rig up a callback for a button press on my GUI. The code is supposed to pass an integer as an argument to let my callback function know which GUI window to reference.

void main_gui()
{
    int number = 5;

    g_signal_connect(button,
                    "clicked",
                    G_CALLBACK(callback_func),
                    (gpointer*) &num);
}

void callback_func(gpointer *data)
{
    int number;
    number = (int*)data;
    printf("Number: %d\n", number);
}

The problem is whenever I try to cast the number to an integer and check the number (via print statement), it returns an incorrect number.

like image 793
Brosta Avatar asked Nov 26 '25 00:11

Brosta


1 Answers

First, does that function actually take a gpointer* or just a gpointer? The latter seems more likely, since gpointer is a void *.

Second, you're passing the address of a local variable &number rather than its value. Don't do that. The local variable is on the stack and will likely not exist once your function exits (which happens before your callback is called). Just pass the value cast as the required type: (gpointer)number Then when you want to use it, cast it back: (int)data

Here's the updated code:

void main_gui()
{
    int number = 5;

    g_signal_connect(button,
                    "clicked",
                    G_CALLBACK(callback_func),
                    //(gpointer*) &num);
                    (gpointer)number);
}

//void callback_func(gpointer *data)
void callback_func(gpointer data)
{
    int number;
    //number = (int*)data;
    number = (int)data;

    printf("Number: %d\n", number);
}
like image 135
Andrew Cottrell Avatar answered Nov 27 '25 21:11

Andrew Cottrell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!