本文介绍了从内存地址创建python对象(使用gi.repository)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

有时,我需要调用仅存在于C中的gtk / gobject函数,但返回一个具有python包装器的对象。以前,我使用了基于效果良好的ctypes的解决方案:

Sometimes I need to call a gtk/gobject function that only exists in C, but returns an object that has a python wrapper. Previously I used a solution based on ctypes that worked well:

现在我从PyGtk(导入gtk)夹到GObject-introspection(从gi.repository导入Gtk),该怎么用呢?

Now that I swiched from PyGtk ("import gtk") to GObject-introspection ("from gi.repository import Gtk"), what can I use instead?

推荐答案

_PyGObject_API 接口在某些时候已更改。我需要删除 register_sinkfunc 函数。以下工作:

The _PyGObject_API interface has changed at some point. I needed to drop the register_sinkfunc function. The following works:

from gi.repository import Gio, GLib
import gi
import ctypes

class _PyGObject_Functions(ctypes.Structure):
   _fields_ = [
       ('register_class',
        ctypes.PYFUNCTYPE(ctypes.c_void_p, ctypes.c_char_p,
                          ctypes.c_int, ctypes.py_object,
                          ctypes.py_object)),
       ('register_wrapper',
        ctypes.PYFUNCTYPE(ctypes.c_void_p, ctypes.py_object)),
       ('lookup_class',
        ctypes.PYFUNCTYPE(ctypes.py_object, ctypes.c_int)),
       ('newgobj',
        ctypes.PYFUNCTYPE(ctypes.py_object, ctypes.c_void_p)),
       ]

class PyGObjectCPAI(object):
   def __init__(self):
       PyCObject_AsVoidPtr = ctypes.pythonapi.PyCObject_AsVoidPtr
       PyCObject_AsVoidPtr.restype = ctypes.c_void_p
       PyCObject_AsVoidPtr.argtypes = [ctypes.py_object]
       addr = PyCObject_AsVoidPtr(ctypes.py_object(
           gi._gobject._PyGObject_API))
       self._api = _PyGObject_Functions.from_address(addr)

   def pygobject_new(self, addr):
       return self._api.newgobj(addr)

capi = PyGObjectCPAI()

要从指针获取对象:

obj = capi.pygobject_new(pointer)

从(g)对象获取指针:

to get a pointer from a (g)object:

pointer = hash(obj)

我必须添加并没有帮助我解决实际问题。我试图与dconf进行接口连接,但是dconf返回的类型为GVariant,它不继承自GObject。不幸的是,似乎PyGI / GObject没有公开将C(* GVariant)转换为Python GLib.Variant所需的函数。我猜是那些时候您不得不放弃最初的方法并尝试一些不同的事情。

I have to add, in my case this didn't help me solve my actual problem. I was trying to interface with dconf, but dconf returns values of type GVariant, which does not inherit from GObject. It seems PyGI/GObject unfortunately does not expose the neccessary functions to turn a C (*GVariant) into a Python GLib.Variant. I guess it's of those times when you have to throw away your initial approach and try something different.

这篇关于从内存地址创建python对象(使用gi.repository)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 06:52