在派生的class中分配虚方法时如何处理"incompatible pointer type"?

How to deal with "incompatible pointer type" when assigning virtual methods in a derived class?

我有 GLib classes FooDerivedFoo.

Fooclass有一个bar ()方法:

typedef struct _FooClass
{
  GObjectClass parent_class;

  void (*bar) (Foo *self);
} FooClass;

DerivedFooclass派生自Foo并实现了bar ()方法:

void derived_foo_bar (DerivedFoo *self);

static void
derived_foo_class_init (DerivedFooClass *klass)
{
  FooClass *foo_class = FOO_CLASS (klass);
  // Compiler warning appears here
  foo_class->bar = derived_foo_bar;
}

警告信息是:

warning: assignment from incompatible pointer type

指针不兼容,因为 self 参数的类型不同(Foo *DerivedFoo *)。

这是在 GObject 中实现虚方法的正确方法吗?

如果是这样,can/should我对编译器警告做些什么?

您保留函数原型以尊重虚拟基础 class,并使用 glib macros/functions.

在您的函数中对其进行类型转换
void derived_foo_bar (Foo *self);

static void
derived_foo_class_init (DerivedFooClass *klass)
{
  FooClass *foo_class = FOO_CLASS (klass);
  // Compiler warning appears here
  foo_class->bar = derived_foo_bar;
}

void derived_foo_bar (Foo *_self)
{
  DerivedFoo *self = DERIVED_FOO (self); /* or whatever you have named this macro, using the standard GLIB semantics */
 /* If self is not compatible with DerivedFoo, a warning will be issued from glib typecasting logic */
}