GTK + g_pointer_connect错误地传递数据 [英] GTK+ g_pointer_connect passing data incorrectly

查看:56
本文介绍了GTK + g_pointer_connect错误地传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用g_signal_connect()时,我无法将数据传递给函数.

I have a problem with passing my data to the function when using g_signal_connect().

guint x = 777;
gpointer ptr = &x;
g_print(std::to_string(*(guint*)p).c_str());
g_signal_connect(G_OBJECT(dialogWindow), "destroy",
    G_CALLBACK(funct), ptr);

这段代码中的g_print输出"777".但是,当 funct 被调用

The g_print in this piece of code outputs "777". However when the funct is called

static void funct(gpointer data) {
  g_print(std::to_string(*(guint*)data).c_str());
}

g_prints输出一些垃圾,例如:"81382720"

the g_prints outputs some garbage like: "81382720"

有人可以帮我吗?

推荐答案

您正在传递一个指向局部变量(x)的指针,并且在堆栈上分配了局部变量.为了使它在该函数范围之外仍然有效,请改为在堆上分配它(或选择使用静态或全局变量).

You're passing a pointer to a local variable (x), and a local variable is allocated on the stack. To keep it alive outside of the scope of that function, allocate it on the heap instead (or optionally use a static or global variable).

guint *ptr = g_malloc(sizeof(guint));
*ptr = 777;
g_print(std::to_string(*ptr).c_str());
g_signal_connect(G_OBJECT(dialogWindow), "destroy",
    G_CALLBACK(funct), ptr);

当您不再需要该指针时,请不要忘记调用g_free来释放该指针,以避免内存泄漏.

Don't forget to call g_free to free that pointer when you don't need it anymore to avoid a memory leak.

我错过了您的回调签名错误的事实,因为它不遵守破坏信号之一.这是一个错误,必须修复.感谢el.pescado指出这一点.

I missed the fact that the signature of your callback is wrong as it doesn't respect the one of the destroy signal. This is a bug and must be fixed. Thanks to el.pescado for pointing that out.

其他帖子上的评论也有效,但不影响正确性:

Remarks on the other posts are valid too, but don't affect correctness:

  • GUINT_TO_POINTER/GPOINTER_TO_UINT可以用于这种简单情况,以避免动态分配
  • 您对g_print的呼叫是不必要的复杂
  • GUINT_TO_POINTER/GPOINTER_TO_UINT can be used for that simple case to avoid dynamic allocation
  • your call to g_print is unnecessary complicated

这篇关于GTK + g_pointer_connect错误地传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆