为什么 io_add_watch() 回调接收到错误的 IOChannel 对象?
Why do io_add_watch() callbacks receive the wrong IOChannel object?
据我所知,从可用文档中可以看出,GLib.io_add_watch() 应该注册一个在 IOChannel 上出现条件时调用的函数,而 callback function 应该接收所述 IOChannel 作为其第一个参数。太好了,只是它没有。 GLib 将一个完全不同的 IOChannel 对象传递给回调。为什么?
换句话说,为什么这段代码会产生 AssertionError?
#!/usr/bin/env python3
import gi
from gi.repository import GLib
_, _, fd, _ = GLib.spawn_async(['/bin/echo', 'hello'], standard_output=True)
channel = GLib.IOChannel.unix_new(fd)
def on_read(callback_channel, condition):
assert callback_channel is channel
GLib.io_add_watch(channel, GLib.PRIORITY_DEFAULT, GLib.IO_IN, on_read)
GLib.MainLoop().run()
IOChannel 是一个 GBoxed 结构,而不是一个 GObject。它没有身份,通过副本传递。您在回调中收到的那个与您提供的那个相同,但它们不是同一个对象,它们的所有字段也不会具有相同的值。
据我所知,从可用文档中可以看出,GLib.io_add_watch() 应该注册一个在 IOChannel 上出现条件时调用的函数,而 callback function 应该接收所述 IOChannel 作为其第一个参数。太好了,只是它没有。 GLib 将一个完全不同的 IOChannel 对象传递给回调。为什么?
换句话说,为什么这段代码会产生 AssertionError?
#!/usr/bin/env python3
import gi
from gi.repository import GLib
_, _, fd, _ = GLib.spawn_async(['/bin/echo', 'hello'], standard_output=True)
channel = GLib.IOChannel.unix_new(fd)
def on_read(callback_channel, condition):
assert callback_channel is channel
GLib.io_add_watch(channel, GLib.PRIORITY_DEFAULT, GLib.IO_IN, on_read)
GLib.MainLoop().run()
IOChannel 是一个 GBoxed 结构,而不是一个 GObject。它没有身份,通过副本传递。您在回调中收到的那个与您提供的那个相同,但它们不是同一个对象,它们的所有字段也不会具有相同的值。