gpt4 book ai didi

glib - 在Gobject中,如何覆盖父类的方法属于一个接口(interface)?

转载 作者:行者123 更新时间:2023-12-04 17:28:50 25 4
gpt4 key购买 nike

GObject 类 A 实现接口(interface) IA,B 是 A 的派生类。 B 如何覆盖作为接口(interface) IA 一部分的 A 的方法?

或者,这在 GObject 中是否可行?

我知道如何重写父类方法,但是当继承遇到接口(interface)时,事情似乎更复杂了。

非常感谢!

最佳答案

是的,有可能:只需像第一次一样重新实现接口(interface),或者使用 G_IMPLEMENT_INTERFACE()或在您的 get_type() 中手动初始化它功能。

真正的痛苦是如果你需要链接旧方法。在这种情况下,你应该玩
g_type_interface_peek_parent 获取之前的接口(interface)类。

这是一个测试用例:

/* gcc -otest `pkg-config --cflags --libs gobject-2.0` test.c */
#include <glib-object.h>


/* Interface */

#define TYPE_IFACE (iface_get_type())

typedef void Iface;
typedef struct {
GTypeInterface parent_class;
void (*action) (Iface *instance);
} IfaceClass;

GType
iface_get_type(void)
{
static GType type = 0;

if (G_UNLIKELY(type == 0)) {
const GTypeInfo info = {
sizeof(IfaceClass), 0,
};

type = g_type_register_static(G_TYPE_INTERFACE, "Iface", &info, 0);
}

return type;
}

void
iface_action(Iface *instance)
{
G_TYPE_INSTANCE_GET_INTERFACE(instance, TYPE_IFACE, IfaceClass)->
action(instance);
}


/* Base object */

#define TYPE_BASE (base_get_type())

typedef GObject Base;
typedef GObjectClass BaseClass;

static void
base_action(Iface *instance)
{
g_print("Running base action on a `%s' instance...\n",
g_type_name(G_TYPE_FROM_INSTANCE(instance)));
}

static void
base_iface_init(IfaceClass *iface)
{
iface->action = base_action;
}

G_DEFINE_TYPE_WITH_CODE(Base, base, G_TYPE_OBJECT,
G_IMPLEMENT_INTERFACE(TYPE_IFACE, base_iface_init));

static void
base_class_init(BaseClass *klass)
{
}

static void
base_init(Base *instance)
{
}


/* Derived object */

#define TYPE_DERIVED (derived_get_type())

typedef Base Derived;
typedef BaseClass DerivedClass;

static void
derived_action(Iface *instance)
{
IfaceClass *iface_class, *old_iface_class;

iface_class = G_TYPE_INSTANCE_GET_INTERFACE(instance, TYPE_IFACE, IfaceClass);
old_iface_class = g_type_interface_peek_parent(iface_class);

g_print("Running derived action on a `%s' instance...\n",
g_type_name(G_TYPE_FROM_INSTANCE(instance)));

/* Chain up the old method */
old_iface_class->action(instance);
}

static void
derived_iface_init(IfaceClass *iface)
{
iface->action = derived_action;
}

G_DEFINE_TYPE_WITH_CODE(Derived, derived, TYPE_BASE,
G_IMPLEMENT_INTERFACE(TYPE_IFACE, derived_iface_init));

static void
derived_class_init(DerivedClass *klass)
{
}

static void
derived_init(Derived *instance)
{
}


int
main()
{
GObject *object;

g_type_init();

object = g_object_new(TYPE_BASE, NULL);
iface_action((Iface *) object);
g_object_unref(object);

object = g_object_new(TYPE_DERIVED, NULL);
iface_action((Iface *) object);
g_object_unref(object);

return 0;
}

关于glib - 在Gobject中,如何覆盖父类的方法属于一个接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1606669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com