问题
I am working on a Gtk project in C.
From the main.c I call a function1 with an int address as a parameter.
In that function1, I can access that first value, but then at the end (inside) of that function1, I call another function2 (which is a callback function to a click event) and pass it the address I got from the function1 parameter.
But in function2, the address have changed, definitely can't figure out why...
My project looks like this :
[main.c]
int main(...) {
int a = 50;
function1(&a);
}
[function1.c]
void function1(int* nb) {
...
g_signal_connect(G_OBJECT(button),"clicked", G_CALLBACK(function2), &nb);
// I know that the 4th arg expects void*, but even though I give the address of that _nb_ parameter, still can't get that 50 in function2
}
[function2.c]
void function2(void* nb) {
...
printf("should got 50 : %d ", *(int*)nb);
// shows random 8 digits number like 60035152
}
EDIT: Forgot to mention that each function is in a separate file, I don't know if that matters as long as I do the includes and gives the prototypes...
Thank you in advance...
回答1:
The problem's in your code are:-
1) you are passing the address of the variable to the callback function so instead of &nb, it should be nb.
2) this is the callback function for clicked signal (https://developer.gnome.org/gtk3/stable/GtkButton.html#GtkButton-clicked_
void
user_function (GtkButton *button,
gpointer user_data)
you are missing an argument in your callback function
回答2:
You have two problems:
First, you're passing the address of a local variable, but this cannot be used after the function returns.
Second, function2
expects nb
to be a pointer to int
, but you're passing a pointer to a pointer to int
to g_signal_connect()
.
void function1(int* nb) {
...
int *nb_copy = malloc(sizeof(int));
*nb_copy = *nb;
g_signal_connect(G_OBJECT(button),"clicked", G_CALLBACK(function2), nb_copy);
// I know that the 4th arg expects void*, but even though I give the address of that _nb_ parameter, still can't get that 50 in function2
}
function_2()
should free(nb);
after it's done with it to prevent a memory leak.
来源:https://stackoverflow.com/questions/59473619/pass-received-argument-to-a-callback-function