Python PyGObject pixbuf 内存泄漏

Python PyGObject pixbuf memory leak

我正在从 gphoto2 检索 JPEG,从数据创建 Gio 流,然后从流创建 Pixbuf:

import gphoto2 as gp
from gi.repository import Gio, GdkPixbuf
camera = gp.Camera()
context = gp.Context
camera.init(context)
file = gp.CameraFile()
camera.capture_preview(file, context)
data = memoryview(file.get_data_and_size())
stream = Gio.MemoryInputStream.new_from_data(data)
pixbuf = GtkPixbuf.Pixbuf.new_from_stream(stream)
# display pixbuf in GtkImage

执行此操作的函数使用 GLib.idle_add(...) 附加到 Gtk 空闲事件。它有效,但它会泄漏内存。该进程的内存使用量不断攀升。即使在构造 pixbuf 的行被注释掉时它也会泄漏,但在构造流的行也被注释掉时不会泄漏,所以看起来是流本身在泄漏。在构建 pixbuf 后添加 stream.close() 没有帮助。

这里释放内存的正确方法是什么?

我不会这样称呼它为答案,如果有人知道问题的直接答案,我很乐意将其标记为正确答案,但这里有一个适用于处于相同位置的其他人的解决方法:

import gphoto2 as gp
from gi.repository import Gio, GdkPixbuf
camera = gp.Camera()
context = gp.Context
camera.init(context)
file = gp.CameraFile()
camera.capture_preview(file, context)
data = memoryview(file.get_data_and_size())
loader = GdkPixbuf.PixbufLoader.new()
loader.write(data)
pixbuf = loader.get_pixbuf()
# use the pixbuf
loader.close()

这不再泄漏内存。