• Re: PyObjects From Python Via ctypes

    From Lawrence =?iso-8859-13?q?D=FFOliveiro?=@ldo@nz.invalid to comp.lang.python on Thu Jun 11 07:44:15 2026
    On Thu, 11 Jun 2026 07:41:20 -0000 (UTC), I wrote:

    I see ctypes has a py_object type, but you can’t seem to do much
    with it. The following might be more useful:

    Example use: accessing a more powerful Cairo wrapper in a context
    where the GUI toolkit wrapper (e.g. PyGObject for GTK) wants to
    give you only a pycairo object.

    ----
    import ctypes as ct
    import qahirah as qah
    from pyobjhack import PyObject

    class PyCairo_Context(ct.Structure) :
    "extract cairo_t pointer from pycairo.Context object."
    _fields_ = \
    [
    ("header", PyObject),
    ("ctx", ct.c_void_p),
    ]

    @classmethod
    def get_ctx(celf, pyctx) :
    return \
    ct.c_void_p(celf.from_address(id(pyctx)).ctx).value
    #end get_ctx

    #end PyCairo_Context

    def pycairo_to_qah(ctx) :
    "returns a qah.Context object wrapping the cairo_t pointer from" \
    " a given cairo.Context object."
    gx = PyCairo_Context.get_ctx(ctx)
    qah.cairo.cairo_reference(gx) # grab one for myself
    return \
    qah.Context(gx)
    #end pycairo_to_qah