我正在用C ++编写一个使用GTK +(不是gtkmm)的应用程序,所以我需要使用g ++编译器进行编译。是否可以使用g ++编译器编译GTK +应用程序? GTK +和库是否与g ++编译器兼容?
我试图在类如下的类中嵌入GTK +函数调用:
#include <gtk/gtk.h>
class LoginWindow
{
public:
LoginWindow();
void on_window_destroy( GtkObject *object, gpointer user_data);
private:
GtkBuilder *builder;
GtkWidget *window;
};
LoginWindow::LoginWindow()
{
builder = gtk_builder_new ();
gtk_builder_add_from_file (builder, "login_window.glade", NULL);
window = GTK_WIDGET (gtk_builder_get_object (builder, "login_window"));
gtk_builder_connect_signals (builder, NULL);
g_signal_connect( GTK_OBJECT(window), "destroy", GTK_SIGNAL_FUNC(on_window_destroy), NULL );
g_object_unref (G_OBJECT (builder));
gtk_widget_show (window);
}
void LoginWindow::on_window_destroy (GtkObject *object, gpointer user_data)
{
gtk_main_quit ();
}
int main (int argc, char *argv[])
{
gtk_init (&argc, &argv);
LoginWindow loginWindow;
gtk_main ();
return 0;
}
我做得对吗?我在线收到编译错误:
g_signal_connect( GTK_OBJECT(window), "destroy", GTK_SIGNAL_FUNC(on_window_destroy), NULL );
login_window.cpp: In constructor "LoginWindow::LoginWindow()":
login_window.cpp:27: error: invalid use of member (did you forget the "&" ?)
这样做的正确方法是什么?
答案 0 :(得分:4)
Gtk +是一个基于C的库,所以你不能把它作为回调的类成员函数。要么将C风格的函数定义为回调,即
extern "C"
void on_window_destroy( GtkObject *object, gpointer user_data)
{
// do yer stuff.. keep in mind, there's no this-pointer here, it's not
// associated with an object
}
在任何类声明之外。注册信号时,您可能希望将LoginWindow对象本身添加为user_data,并在输入方法时将其强制转换为 转发电话,就像这样
extern "C"
void on_window_destroy( GtkObject *object, gpointer user_data)
{
static_cast<LoginWindow*>(user_data)->on_window_destroy();
}
如果你想做c ++风格,看看gtkmm,它是Gtk +的c ++包装器,它会为你提供更多的OOP。使用gtkmm中的信号/回调更麻烦,但它的类型安全,最终会为您节省很多麻烦。