[Python] Cannot create pointer type for a Structure subclass within __init_subclass__ using...

Discussão em 'Python' iniciado por Stack, Maio 27, 2025.

  1. Stack

    Stack Membro Participativo

    import ctypes
    from ctypes.wintypes import *

    class xStructure(ctypes.Structure):
    def __init_subclass__(cls):
    p = ctypes.POINTER(cls)

    class OFFSET_VAL_II_C4(xStructure):
    _fields_ = [('ValOrig', DOUBLE),
    ('MaxChangeVal', DOUBLE),
    ('ActChangeVal', DOUBLE)]


    The code above results in TypeError: _type_ must have storage info triggered by line 6 (p = ctypes.POINTER(cls)).

    However, the code below works just fine.

    import ctypes
    from ctypes.wintypes import *

    class xStructure(ctypes.Structure):
    pass

    class OFFSET_VAL_II_C4(xStructure):
    _fields_ = [('ValOrig', DOUBLE),
    ('MaxChangeVal', DOUBLE),
    ('ActChangeVal', DOUBLE)]

    p = ctypes.POINTER(OFFSET_VAL_II_C4)


    My researches into the specific TypeError suggested it is caused by an attempt to create a pointer type for something that is not a ctype. However, in this case, OFFSET_VAL_II_C4 is a subclass of ctypes.Structure (via xStructure), so should work - and does, as evidenced by the second example.

    What am I missing?

    (For those wondering why I want to do this, there is a reason that I am happy to elaborate, but I am well aware that the minimal code here is utterly pointless!)

    Continue reading...

Compartilhe esta Página