Search code examples
pythonc++ctypes

Converting PyCapsule to ctypes.c_void_p


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

I tried the following casts in Python, but to no avail

addr = ctypes.py_object(capsule)

Solution

  • Thank you. The following implementation worked.

    ctypes.pythonapi.PyCapsule_GetName.restype = ctypes.c_char_p
    ctypes.pythonapi.PyCapsule_GetName.argtypes = [ctypes.py_object]
    name = ctypes.pythonapi.PyCapsule_GetName(capsule)
    
    ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.c_void_p
    ctypes.pythonapi.PyCapsule_GetPointer.argtypes = [ctypes.py_object, ctypes.c_char_p]
    addr = ctypes.pythonapi.PyCapsule_GetPointer(capsule, name)
    
    addr = ctypes.c_void_p(addr)