Converting ctypes.c_void_p to PyCapsule

Viewed 153

I have a python method in one library that returns a function handle as a ctypes.c_void_p. I need to pass the handle to another library that expects it as a capsule. How can I convert the c_void_p into a capsule to facilitate this interop?

1 Answers

Like this:

import ctypes
PyCapsule_Destructor = ctypes.CFUNCTYPE(None, ctypes.py_object)
PyCapsule_New = ctypes.pythonapi.PyCapsule_New
PyCapsule_New.restype = ctypes.py_object
PyCapsule_New.argtypes = (ctypes.c_void_p, ctypes.c_char_p, PyCapsule_Destructor)
capsule = PyCapsule_New(0xdeadbeef, None, PyCapsule_Destructor(0))
Related