| 1 |
import ctypes |
| 2 |
|
| 3 |
import cairo # pycairo |
| 4 |
|
| 5 |
import cairocffi |
| 6 |
|
| 7 |
pycairo = ctypes.PyDLL(cairo._cairo.__file__) |
| 8 |
pycairo.PycairoContext_FromContext.restype = ctypes.c_void_p |
| 9 |
pycairo.PycairoContext_FromContext.argtypes = 3 * [ctypes.c_void_p] |
| 10 |
ctypes.pythonapi.PyList_Append.argtypes = 2 * [ctypes.c_void_p] |
| 11 |
|
| 12 |
|
| 13 |
def _UNSAFE_cairocffi_context_to_pycairo(cairocffi_context): # noqa: N802 |
| 14 |
# Sanity check. Continuing with another type would probably segfault. |
| 15 |
if not isinstance(cairocffi_context, cairocffi.Context): |
| 16 |
raise TypeError('Expected a cairocffi.Context, got %r' |
| 17 |
% cairocffi_context) |
| 18 |
|
| 19 |
# Create a reference for PycairoContext_FromContext to take ownership of. |
| 20 |
cairocffi.cairo.cairo_reference(cairocffi_context._pointer) |
| 21 |
# Casting the pointer to uintptr_t (the integer type as wide as a pointer) |
| 22 |
# gets the context’s integer address. |
| 23 |
# On CPython id(cairo.Context) gives the address to the Context type, |
| 24 |
# as expected by PycairoContext_FromContext. |
| 25 |
address = pycairo.PycairoContext_FromContext( |
| 26 |
int(cairocffi.ffi.cast('uintptr_t', cairocffi_context._pointer)), |
| 27 |
id(cairo.Context), |
| 28 |
None) |
| 29 |
assert address |
| 30 |
# This trick uses Python’s C API |
| 31 |
# to get a reference to a Python object from its address. |
| 32 |
temp_list = [] |
| 33 |
assert ctypes.pythonapi.PyList_Append(id(temp_list), address) == 0 |
| 34 |
return temp_list[0] |