How to send user_data with gtk signals in loop

生来就可爱ヽ(ⅴ<●) 提交于 2021-01-29 16:20:47

问题


I have signals "make" and "send" registered in core class in main thread. I call call_make() from user class in same thread. call_make() will do some work and fetch some data from worker thread and after return it will emit signal "make".

This is code of user class

struct my_struct{
   int cur_make_id;
   int cur_send_id;    //there may be many id's if multiple signals
}

void on_send_cb(core, gpointer data){
   my_struct *user_data = (my_struct *) data;
   printf("cure_make_id %d", user_data->cur_make_id);   \\ this prints "4" everytime  
   printf("cure_send_id %d", user_data->cur_send_id);   \\ this prints "2" everytime  
}

void on_make_cb(core, gpointer data){
   my_struct *user_data = (my_struct *) data;
   printf("cure_make_id %d", user_data->cur_make_id);   \\ this prints "4" everytime  
   for(int index=0;index<3;index++){
       call_send();
       user_data->cur_send_id = index;
       g_signal_connect(core, "send", G_CALLBACK(on_send_cb), user_data );
   }     
}

void function(){
   my_struct *user_data = g_malloc0(sizeof(my_struct));
   for(int index=0;index<5;index++){
       call_make();
       user_data->cur_make_id = index;
       g_signal_connect(core, "make", G_CALLBACK(on_make_cb), user_data );
   }
}

I get wrong cur_make_id and cur_send_id for all signals (getting last index of for loop)

I know signal_emit and connect delayed and for loop moved forward. I want to know how can I share this user_data to callback so that I can know that this callback is for which index?

(for simplicity I made these call_make() api's, I can't change arguments of api's)


回答1:


Assuming you are only talking about the user_data provided during connecting the callback, you have wrong memory allocation:

void function(){
   my_struct *user_data = g_malloc0(sizeof(my_struct));
   for(int index=0;index<5;index++){
       call_make();
       user_data->cur_make_id = index;
       g_signal_connect(core, "make", G_CALLBACK(on_make_cb), user_data );
   }
}

In this function you have only 1 single block of memory that is passed to all connected callback functions. Whenever the callbacks are called, they will see whatever was written there last. In your case this will be index=4.

To provide different data for different handlers, you actually need to allocate different data:

void function(){
   for(int index=0;index<5;index++){
       my_struct *user_data = g_malloc0(sizeof(my_struct));
       call_make();
       user_data->cur_make_id = index;
       g_signal_connect(core, "make", G_CALLBACK(on_make_cb), user_data);
   }
}

If you also have problems providing data from the function triggering the signal, you need to show more code.



来源:https://stackoverflow.com/questions/62082474/how-to-send-user-data-with-gtk-signals-in-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!