Search code examples
pythonctypes

Is it acceptable to subclass c_void_p in ctypes?


I am interfacing with a library that returns opaque pointers. Is it acceptable to subclass c_void_p to represent this in ctypes and provide for type checking for this particular flavor of c_void_p?


Solution

  • An easy way to do this type checking might be to create some arbitrary ctypes.Structure

    class _Opaque(ctypes.Structure):
        pass
    

    Declare the return type of the relevant functions to be a pointer to this structure

    lib.f.restype = ctypes.POINTER(_Opaque)
    

    and either the argument type of a function which accepts this kind of pointer again:

    lib.g.argtypes = [ctypes.POINTER(_Opaque)]
    

    Now, ctypes ensures that the parameter to g is a pointer that was returned by f before. (Note that I used a leading _ to mark _Opaque for uses in this module only.)