I'm trying to pass multiple values to a function when gtk_button click event invoke. The value are type of struct, int and gtk_image. I have a set of gtk images which attached to a table. The code fraction is as below,
`
GtkWidget *coin[6][7];
....
for(i=0;i<6;i++){
for(j=0;j<7;j++){
coin[i][j] = gtk_image_new_from_file("CoinC.png");
gtk_table_attach_defaults (GTK_TABLE(boardTable), coin[i][j], j, j+1, t, t+1);
}
t-=1;
}
`
I have created buttons to do some function and in the function involve some widgets set properties. One of it is I would like to change my image display as per code below
gtk_image_set_from_file(coin[slot][b->heights[0]],"CoinB.png");
The event fire code for button is as per below
gtk_signal_connect (GTK_OBJECT(button[0]), "clicked", GTK_SIGNAL_FUNC(dropCoin(b,0,coin)),NULL);
And the dropCoin function is as per below
gint dropCoin(board_type *b, gint slot, GtkWidget *coin[6][7]){
if(cp(b)==PLAYER_ONE){
makeMove(b,slot);
gtk_image_set_from_file(coin[slot][b->heights[0]-1],"CoinB.png");
}else{
makeMove(b, getReasonedMove(b));
gtk_image_set_from_file(coin[slot][b->heights[0]-1],"CoinA.png");
}
return 0;
}
Everytime I compile and run the program, the event straightway fired up without any clicking action being done. And when I tried to click back the same button, the event is not fired. I also received below error g_cclosure_new: assertion callback_func != NULL failed and
g_signal_connect_closure_by_id:assertion `closure != NULL' failed
Is there any other way to pass multiple values with widget to the event function.
What you're doing is using the return value from a call to dropCoin() as the function pointer.
You are not in any way telling GTK+ that it should call dropCoin() with the indicated parameters at a later time: the call happens right there before gtk_signal_connect() runs.
Signal callbacks only have a single user-settable parameter: the gpointer user_data. You need to find a way to associate all your desired data with that single pointer, typically by allocating some memory to hold the data and passing a pointer to that memory. In C, this is of course typically done by declaring a struct, and then allocating an instance of it.
Btw, your code is using an old version of GTK+, you should consider upgrading to 3.x.
You must give a function pointer to GTK_SIGNAL_FUNC. What you do is calling dropCoin and passing the resulting int to GTK_SIGNAL_FUNC.
Your call should look more like
gtk_signal_connect (GTK_OBJECT(button[0]), "clicked", GTK_SIGNAL_FUNC(dropCoin),NULL);
You can pass only one parameter, but you can wrap more than one value into a struct and pass that instead.
Update:
The function will be called with the argument you passed to gtk_signal_connect
struct send_Data {
board_type *b;
gint slot;
GtkWidget *coin;
};
struct send_Data arg;
gtk_signal_connect (GTK_OBJECT(button[0]), "clicked", GTK_SIGNAL_FUNC(dropCoin), &arg);
and dropCoin is defined as
void dropCoin(struct send_Data *arg){
...
// do something with arg
makeMove(arg->b, arg->slot);
foo(arg->b);
bar(arg->coin);
...
}
Related
I have a function called create_interface. In that function is a signal handler for the Open menu button (the menu is created in create_interface). I want to pass the window widget and also pass along the tree view widget, because when you open a file an entry in the tree view is supposed to show up. I tried passing them as a struct, but, although its works, GTK generates some error messages.
// This is global.
struct everything
{
GtkWidget *window;
GtkWidget *tree_view;
}
GtkWidget *create_interface (void)
{
struct everything instance;
struct everything *widgets;
widgets = &instance;
...code here...
g_signal_connect(file_mi_open_file_dialog, "clicked", G_CALLBACK(open_file_dialog), widgets);
The function open_file_dialog looks like this:
void open_file_dialog (GtkWidget *wid, gpointer data)
{
struct everything *sample_name = data;
...rest of code here...
I was wondering if there was another way of organizing a program so you do not have to have global variables.
I tried passing them as a struct, but, although its works, GTK generates some error messages.
The problem is that you're trying to use a stack-allocated struct, which becomes invalid after the create_interface() function is done, while you would normally expect these values to still be valid at a later moment in time (for example, when open_file_dialog() is called.
I was wondering if there was another way of organizing a program so you do not have to have global variables.
One possible solution is indeed to use a global variable: this will be valid throughout the lifetime of the program, but it has major drawbacks: it doesn't scale if you have to do that for each callback, and it's architecturally not really clean.
Another solution is to allocate your "closure" (i.e. the variables you want to capture at the moment you create your callback) on the heap, and to free it when you're done with it. GLib even helps you with this by a call g_signal_connect_data() (or g_signal_connect_object() if you save your fields in a GObject)
// Technically you don't need the typedef
typedef struct _ClickedClosure {
GtkWidget *window;
GtkWidget *treeview;
} ClickedClosure;
GtkWidget *create_interface (void)
{
// Note that the g_new0 allocates on the heap instead of using the stack
ClickedClosure *closure = g_new0 (ClickedClosure, 1);
// code here to initialize your window/treeview ...
// put the widgets in the closure
closure->window = my_window;
closure->treeview = treeview;
// Connect to the signal
g_signal_connect_data(file_mi_open_file_dialog, "clicked",
G_CALLBACK(open_file_dialog), closure, g_free, 0);
}
void open_file_dialog (GtkWidget *wid, gpointer data)
{
// Since this was allocated on the heap, this is still valid
ClickedClosure *sample_name = data;
// code handling here ...
}
Very often, what developers using GTK do, is that they're using their own GObject classes/objects already, which they can then use with g_signal_connect_object(), or by manually freeing it with g_object_unref() later. Using GObject then also allows you to to a runtime-typecheck cast, which makes sure your closure has the right type.
I am currently building my own GUI using the SDL2 library for a program i wrote in C (c89).
Problem
I want to let the user of my code pass its own click handler function, which would be called every time a click event is fired on the surface of the corresponding button.
What I tried
I thought i could use function pointers like this :
bind_ClickHandler(void (*function)(void)) {/* bind it to a button */}
but, obviously, it is too limiting for the user.
So i tried to use stdarg.h :
/* ... : arguments to pass to the click handler */
bind_ClickHandler(void (*function)(), int nb_args, ...)
{
void *arg_pt;
va_list args;
va_start(args, nb_args);
/* I don't know what to do so i cast it as a garbage pointer */
arg_pt = va_arg(args, void *);
/* repeat this in a loop to save the args and bind the click handler to a button */
}
With this code i can pass arguments to the click handler, but only if i know their types.
What I want
I want to use something like the second piece of code i showed you to save the args to pass to the click handler, but it doesn't work because i need to know the types of the args to use va_arg().
Just pass a single void* pointer. Like qsort_r or pthread_create[*]. The user only needs one pointer - and that pointer will point anywhere the user wants to.
void (*clickhandler_user_function)(void *) = NULL;
void *clickhandler_user_function_arg = NULL;
void bind_ClickHandler(void (*function)(void*arg), void *function_arg) {
// store function and fucntion_arg somewhere
clickhandler_user_function = function;
clickhandler_user_function_arg = function_arg;
}
A single pointer is just enough:
struct user_context_s {
int some_number;
const char *some string;
// etc.
};
void user_function_that_operates_on_user_context(void *p) {
struct user_context_s *ctx = p;
printf("My number is: %d\n", ctx->some_number);
}
int main() {
// user can use malloc() and manage the lifetime of it's context
struct user_context_s ctx = {1, "blabla"};
bind_ClickHandler(user_function_that_operates_on_user_context, &user_context);
}
[*] - or thrd_create or fopencookie uses void *cookie or the standard sigevent uses void *sival_ptr; in sigval to pass context when sigev_notify == SIGEV_THREAD.
I have the following code:
gpointer w[3];
GtkWidget *menu_item = gtk_menu_item_new();
w[0] = menu_item;
menu_item = gtk_menu_item_new();
w[1] = menu_item;
GtkTextBuffer *buffer = gtk_text_buffer_new(NULL);
w[2] = buffer;
This is all good till now. Let's now connect a signal:
g_signal_connect(w[0], "activate", G_CALLBACK(runner), w);
runner function is declared as:
void runner(gpointer root, gpointer w[]);
Testing the values of w array before entering runner and while in it shows that they (the values) are different. I need them to be the same. How can I accomplish that, and why they aren't identical? Also, segfault occurs.
I created a small program that is bare bones of the original one and that is supposed to recreate the conditions such that the problem occurs. Oddly enough, it runs fine.
#include <gtk/gtk.h>
void carry(gpointer root, gpointer a[])
{
g_print("\n");
g_print("%d\n", root);
g_print("%d\n", a[0]);
g_print("%d\n", a[1]);
g_print("%d\n", a[2]);
}
int main(int argc, char **argv)
{
gtk_init(&argc, &argv);
GtkWidget *menu_item;
GtkTextBuffer *buffer;
gpointer abc[3];
menu_item = gtk_menu_item_new();
abc[0] = menu_item;
g_print("%d\t%d\n", menu_item, abc[0]);
menu_item = gtk_menu_item_new();
abc[1] = menu_item;
g_print("%d\t%d\n", menu_item, abc[1]);
buffer = gtk_text_buffer_new(NULL);
abc[2] = buffer;
g_print("%d\t%d\n", buffer, abc[2]);
g_signal_connect(abc[2], "modified-changed", G_CALLBACK(carry), abc);
gtk_text_buffer_set_modified(abc[2], TRUE);
gtk_main();
return 0;
}
Which means that something else is problematic. I'll try something else now, like commenting lines and leaving only the relevant ones.
I didn't comment any lines yet, but I tried putting g_print in both the caller and the callee.
This is an output:
1162863440 1162863440
1162864736 1162864736
1163320992 1163320992
1162863440
-2
1162668992
973486176
The first three lines compare the original values with their copies in the array (in the sense of g_print("%d\t%d\n", menu_item, abc[0]); from the code above). As you can see, everything is assigned correctly. After a new line, we check those same values in the callee. root, the first parameter, always has the correct value. So there's no problem with that. abc[0] in the callee always has the value of -2. Seriously, every time I run the program it is -2. Other two (abc[1] and abc[2]) always have some garbage random values, but they change every time I run the program unlike abc[0].
I hope this will help in diagnosing and fixing the problem.
I tried passing both abc[0] and abc normally through a function (func(arg0, arg1, ...) instead of using g_signal_connect()) and there is no problem whatsoever.
This all can mean only one thing: g_signal_connect is messing with my values. It changes them for some unknown reason.
I guess I'll have to use a struct.
You're not supposed to use gpointers everywhere. A gpointer is a void *, so you're pretty much disabling all the type checking the compiler could do for you. Use GtkWidget * instead, and do proper casts using G_OBJECT(), GTK_TEXT_BUFFER() etc. macros.
You should also use typed callback arguments, as they appear in the documentation for each signal. For example for the activate signal:
void
user_function (GtkMenuItem *menuitem,
gpointer user_data)
And if you want to pass several items in the user-data field, pass a pointer or pointer to a structure instead of an array of pointers.
And if you have a segfault, well, just use a debugger to check where the problem is.
The problem is: what's the best way to share data between functions, but specifically in GTK/C application? The best means the most 'proper', the fastest in run and/or absorbing as low CPU power as possible.
I'm asking because I have to code some app with GUI under linux, but I'm rather a microcontroller programmer (and maybe it's hard to me to think like big computer). In small 8-bit MCU's world, where code is in plain C, globals are the fastest and commonly used way to share data between functions.
But I guess that in much more complicated app running under operating system there must be other 'special' way to do that. To this point I noticed that GTK (GDK, Glib etc.) offer many special functions and build-in mechanisms to makes programmer's life easiest, so I suppose it should be something elegant for sharing variables between functions.
Searching through the net I've seen different solutions:
- classes with private variables and methods to get/set them - but my app is coded in C, not C++, I'd like to avoid using object programming,
- global structs or even one big global struct with many members,
- good plain globals,
- GtkClipboard, but I think it's for different purposes.
What I want to do is simply to set some variable 'A' in one callback function, set that variable once again in second callback, and then in another callback do something depending upon value of variable 'A', like this:
callback_func1{
//...
A = some_func();
//...
}
callback_func2{
//...
A = another_func();
//...
}
callback_func3{
//...
if(A>threshold) do_something();
else do_nothing();
//...
}
You're right to be wary of globals, especially if you only want to allow certain functions to be modifying them.
Assuming you're retaining more data than just A (which for simplicity I've defined as int), you can set up your structure in the familiar way
typedef struct t_MYCBSD
{
int A;
// other members
} MYCBSD; // callback struct data
including other data members as necessary. (I've included the t_MYCBSD in case there is some self-referencing).
You can then implement your callback functions as follows:
void callback_func1( GtkWidget *widget, gpointer user_data )
{
MYCBSD *data = user_data;
data->A = some_func();
}
void callback_func2( GtkWidget *widget, gpointer user_data )
{
MYCBSD *data = user_data;
data->A = another_func();
}
void callback_func3( GtkWidget *widget, gpointer user_data )
{
MYCBSD *data = user_data;
if( data->A > threshold ) do_something();
else do_nothing();
}
Obviously, some_func(), another_func(), threshold, do_something() and do_nothing() are valid in this context.
NOTE: the data pointer to your struct makes the syntax a little more clear. You can also use:
((MYCBSD *) user_data)->A = some_func();
In any case, you usually set up your callbacks when creating your widgets. In the following (heavily culled, non-GtkBuilder) code, MYCBSD mydata will be locally scoped. I'm assuming the callbacks will be set for some buttons with the "clicked" event.
int main( int argc, char* argv[] )
{
MYCBSD mydata;
// Below-referenced widgets
GtkWidget *mywidget1, *mywidget2, *mywidget3;
// ... other widgets and variables
mydata.A = 0; // Optionally set an initial value to A
// Standard init via gtk_init( &argc, &argv );
// ... Create the toplevel and a container of some kind
// Create mywidget1,2,3 (as buttons, for example)
mywidget1 = gtk_button_new_with_label ("widget1");
mywidget2 = gtk_button_new_with_label ("widget2");
mywidget1 = gtk_button_new_with_label ("widget3");
g_signal_connect( mywidget1, "clicked", G_CALLBACK(callback_func1), &mydata );
g_signal_connect( mywidget2, "clicked", G_CALLBACK(callback_func2), &mydata );
g_signal_connect( mywidget3, "clicked", G_CALLBACK(callback_func3), &mydata );
// ... Attach those widgets to container
// ... and show all
// Run the app in a standard way via gtk_main();
return 0;
}
The important lines here are:
g_signal_connect( mywidget1, "clicked", G_CALLBACK(callback_func1), &mydata );
g_signal_connect( mywidget2, "clicked", G_CALLBACK(callback_func2), &mydata );
g_signal_connect( mywidget3, "clicked", G_CALLBACK(callback_func3), &mydata );
where the last parameter passes your data to the callback functions.
If you're only looking to share a single value, A, you can pass that in a similar way without the need of a struct.
If you want to use globals, just use globals. And, regardless of what the world says, nobody died because used globals.
Globals are avoided because make maintenance hard on big programs and, from your description, this just does not seem to be the case.
On the sharing side, GTK+ programs are usually not parallel, so you can freely access globals in RW without problems. And also when tasks are used, it is best practice to put all the GTK+ calls on the same task: you are still allowed to access globals in RW from the same task.
I am building a GTK program that does the following: A button gets clicked by the user, it retrieves information from the server, then creates new buttons that the user can click on. I technically have a signal in main, and in that call_back I have multiple signals (for each of the created buttons).
I would like to pass data to this new button, but here it becomes icky. If I create a struct inside my first button I will later crash in the buttons that are generated because the struct is locally defined on the stack, and so it gets deleted.
I cannot create a global variable as each of the created button need different values. I basically would like to pass a struct with multiple fields when my initial button (callback method) gets called, but each of this struct is different.
The only way I can think of is to allocate it on the heap, but it becomes a bit of overhead to know when to free it.
Is there a good way around this please, or am I following wrong design choices for GTK by having a signal handler create a new signal handler please?
Thank you very much.
EDIT:
I am still crashing, and I am very confused why.
This is the code for the main button:
struct buttonData* data = (struct buttonData*) malloc(sizeof(struct buttonData));
data->IP = strdup(newDevice.IP.c_str()); // Added strdup
data->port = atoi(newDevice.port.c_str());
g_signal_connect(G_OBJECT(deviceButton), "button_press_event", G_CALLBACK(showDeviceAndConnect), (gpointer) data);
Code for the button that is generated:
static void showDeviceAndConnect(GtkWidget * deviceButton, gpointer data) {
struct buttonData* toConnect = (struct buttonData *) data;
fprintf(stderr, "IP: %s, PORT: %d\n", toConnect->IP, toConnect->port); //SIGSEGV
}
I am not sure why. Any help would be very appreciated.
The reason for the crash is the signature of your callback. "button-press-event" expects the callback with the signature gboolean foo(GtkWidget* , GdkEvent*, gpointer). As you callback has signature of void foo (GtkWidget * , gpointer ) the second parameter which you are getting in the callback function is not gpointer data which used when registering callback but GdkEvent pointer. Thus when you are dereferencing GdkEvent pointer (thinking it as the data you had passed) you are seeing the crash. So to fix this issue change static void showDeviceAndConnect(GtkWidget * deviceButton, gpointer data) to static void showDeviceAndConnect(GtkWidget * deviceButton, GdkEvent *ev, gpointer data).
Alternatively, as you are using only data in showDeviceAndConnect function you can using g_signal_connect_swapped which will pass the data as the first parameter; so if you use g_signal_connect_swapped your function static void showDeviceAndConnect(GtkWidget * deviceButton, gpointer data) can be static void showDeviceAndConnect(gpointer data).
Hope this helps!
The only way I can think of is to allocate it on the heap, but it becomes a bit of overhead to know when to free it.
That is the way to do it. Allocate the structure on the heap and pass a pointer to it as the callback data. Note that even while it does not apply to you since you are dynamically generating those buttons, using global variables is a poor choice as a solution.