Re: PyObjects From Python Via ctypes

Lawrence D’Oliveiro <[email protected]> Thu, 11 Jun 2026 07:44:15 -0000 (UTC)
Newsgroups comp.lang.python
Organization A noiseless patient Spider
Message-ID <[email protected]>
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