c - 如果 GInterface 方法签名与 VirtualTable (struct) 方法不匹配怎么办?

标签 c glib gobject gio

我决定回到GObject中GInterfaces的基础知识,所以我又去看了一遍基础教程。在 this chapter你可以看到如何定义一个非常简单的 GInterface。

如您所见,方法 maman_ibaz_do_actionmaman_ibaz_do_something 的签名分别与符号 _MamanIbazInterface.do_action 的签名匹配和 _MamanIbazInterface.do_something

但如果他们不这样做会怎样?我有一个真实世界的例子。 GInterface 是 gpollableinputstream ( source here )。特别是 read_nonblocking() 方法,它在 VT 中有 4 个参数,但后来在头函数中有 5 个参数。

那么,如果这个接口(interface)的实现者覆盖了前者(real world example here),那么其他人怎么能从其他类调用这个实现呢?

最佳答案

这里的代码有点不寻常,但基本上一切都按您预期的那样工作。

要调用g_converter_input_stream_read_nonblocking,您可以选择

  • 通过 GConverterInputStream 实例的接口(interface)指针调用它:

    GConverterInputStream *my_gcis;
    
    ...
    
    bytes_read =
      G_POLLABLE_INPUT_STREAM_GET_INTERFACE (my_gcis)->
        read_nonblocking (my_gcis, buffer, count, error);
    

  • 通过接口(interface)方法调用它,g_pollable_input_stream_read_nonblocking,它添加了第五个参数和一些额外的功能:

    bytes_read =
      g_pollable_input_stream_read_nonblocking (G_POLLABLE_INPUT_STREAM (my_gcis),
                                                buffer,
                                                count,
                                                cancellable,
                                                error);
    

第二种方法之所以有效,是因为在内部 g_pollable_input_stream_read_nonblocking 调用了接口(interface)定义的正常“四参数”版本函数,位于gpollableinputstream.c:212。 :

res = G_POLLABLE_INPUT_STREAM_GET_INTERFACE (stream)->
  read_nonblocking (stream, buffer, count, error);

一个接口(interface)的方法提供比这更多的功能是不寻常的,但除此之外,这里的一切都像往常一样工作。

关于c - 如果 GInterface 方法签名与 VirtualTable (struct) 方法不匹配怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25149386/

相关文章:

c - 如何使用 autotools 正确设置 GLib 测试框架

python - 如何使用 Kupfer (python) 修复 TypeError : glib. spawn_async?

c - 如何用关键操作替换ClutterTexture?

Python 线程不适用于 pygobject?

memory-management - 何时释放 GObject?

C:将 RGB 值的结构写入文件以创建 ppm 图像 - 文件过早结束

c: 使用递归反转字符串?

c - 使用 Javascriptcore Glib API 返回 native 对象

c - 这是什么意思 : (void *) 0x00

c - 在生成过程中获取值