成员函数作为g_signal_connect的回调函数 [英] member function as callback function to g_signal_connect

查看:920
本文介绍了成员函数作为g_signal_connect的回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个用于创建gtk主窗口的简单类.

I have created a simple class for creating gtk main window.

我想知道将类成员函数作为参数传递给G_CALLBACK函数的正确方法是什么?

I want to know what is correct way to pass class member function as an argument to G_CALLBACK function?

为什么

g_signal_connect(按钮,单击",G_CALLBACK(& MainWindow: nButtonClicked),NULL);

g_signal_connect(button, "clicked", G_CALLBACK(&MainWindow: nButtonClicked), NULL);

不好吗?

#include <gtk/gtk.h>

class MainWindow {
public:
    MainWindow();
    ~MainWindow();
    void onButtonClicked(GtkWidget* button, gpointer* data);
    void showWindow();

private:
    GtkWidget* window;
    GtkWidget* button;
};
MainWindow::MainWindow()
{
    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    g_signal_connect(window, "delete_event", G_CALLBACK(gtk_main_quit), NULL);

    button = gtk_button_new_with_label("click here");
    g_signal_connect(button, "clicked", G_CALLBACK(&MainWindow: nButtonClicked), NULL);

    gtk_container_add(GTK_CONTAINER(window), button);
}

MainWindow::~MainWindow()
{
}

void MainWindow::onButtonClicked(GtkWidget* button, gpointer* data)
{
    g_printerr("button clicked\n");
}

void MainWindow::ShowWindow() {
    gtk_widget_show_all(window);
}

int main(int argc, char* argv[]) {
    gtk_init(&argc, &argv);

    MainWindow mainWindow;
    mainWindow.showWindow();

    gtk_main();
    return 0;
}

推荐答案

您必须传递一个静态函数和此指针:

You have to pass a static function and the this-pointer:

class Window 
{
    public:
    virtual void on_button_clicked(GtkWidget* button);

    void connect_button_clicked(GtkWidget* button) {
        g_signal_connect(
            button, 
            "clicked", 
            G_CALLBACK(button_clicked_callback), this);
    }

    private:
    static void button_clicked_callback(GtkWidget* button, gpointer* data) {
        reinterpret_cast<Window*>(data)->on_button_clicked(button);
    }
};

将指针传递给成员函数将不起作用(类型不兼容且没有对对象的引用).如果c回调机制不支持自定义数据(此处为this指针),那么事情将变得很丑陋.

Passing a pointer to a member function will not work (incompatible types and no reference to an object). If the c-callback mechanism does not support custom data (the this pointer here) things will get ugly.

这篇关于成员函数作为g_signal_connect的回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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