简体   繁体   中英

Passing integer as gpointer in g_signal_connect

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.

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);
}

You have got two errors, it should be (gpointer) &number in main_gui and number = *((int*)data) in callback_func. I would also do static int number = 5 :

void main_gui()
{
    static int number = 5;

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM