GLib 对象无法创建可派生类型对象,得到“GLib-GObject-CRITICAL:无效的未分类类型”

问题描述 投票:0回答:1

我尝试创建一个简单的可导出类型,但我似乎错过了一些东西。 当我尝试调用虚拟方法时,“MY_ITEM_CLASS(结果)”抛出严重错误。

编译

gcc `pkg-config glib-2.0 gtk4 --cflags` test_gtk.cpp -o test_gtk `pkg-config glib-2.0 gtk4 --libs` -lstdc++

错误信息是

GLib-GObject-CRITICAL **:16:01:24.795:类中无效的未分类类型“(null)”转换为“MyItem”

#include <glib-object.h>

#include <iostream>
 
typedef struct _MyItem MyItem;
#define MY_TYPE_ITEM (my_item_get_type())
G_DECLARE_DERIVABLE_TYPE(MyItem, my_item, MY, ITEM, GObject)

struct _MyItemClass {
    GObjectClass parent;
    void (*print)(MyItem* self);
};
 
typedef struct { 
    const char* name;    
} MyItemPrivate;

auto static my_item_init (MyItem *object) -> void;
auto static my_item_class_init (MyItemClass* klass) -> void;

G_DEFINE_TYPE_WITH_PRIVATE (MyItem, my_item, G_TYPE_OBJECT)


auto static item__print(MyItem* self) -> void {
    auto priv = (MyItemPrivate*)my_item_get_instance_private(self);
    std::cout << (priv->name?priv->name:"unnamed") << std::endl;
}

auto static my_item_init (MyItem *object) -> void {
    auto priv = (MyItemPrivate*)my_item_get_instance_private(object);
    priv->name = "This is my name";
}

auto static my_item_class_init (MyItemClass* klass) -> void {
    GObjectClass *object_class = G_OBJECT_CLASS(klass);
    klass->print = item__print;
}



auto main() -> int {
    auto result = (MyItem*)g_object_new(MY_TYPE_ITEM, nullptr);
    MY_ITEM_CLASS(result)->print(result);
    g_object_unref(result);    
    return 0;
}
c++ gtk glib gnome gobject
1个回答
0
投票

它不起作用,因为而不是

MY_ITEM_CLASS(result)->print(result);

一定是

MY_ITEM_GET_CLASS(result)->print(result);

又是一个耗时数小时的错误,表明我患有阿尔茨海默病,需要找到另一份工作。

© www.soinside.com 2019 - 2024. All rights reserved.