python - Is it at all possible to create indirectly recursive ctypes.Structure types? -
this not same #1228158 or #28879604. it's similar, twist.
it's trivial create recursive type referring own type:
a = type('a', (ctypes.structure,), {}) a._fields_ = [('another_a', ctypes.pointer(a))]
or, if prefer:
class a(ctypes.structure): pass a._fields_ = [('another_a', ctypes.pointer(a))]
same thing. if they're not same thing, educate me!
but i'm trying machine-translate c struct
s , typedef
s ctypes.structure
s. want names , relations on python side reflect on c side. if function returning uint32
typedef
ed consumer_id
, want object on python side have more descriptive name. now, here's type of thing occurs quite often:
typedef dummy_type official_type; typedef struct dummy_struct { official_type *another_struct; } dummy_type;
no matter how twist , turn this, can't realize relation in python. intermediate names probably not used anywhere, @ moment we're going idea of detecting situation , making official_type
ctypes.structure
referring itself. , maybe make dummy_type
, struct dummy_struct
types referring themselves. on binary level, on c side, they'll equivalent.
but want this:
struct_dummy_struct = type('struct_dummy_struct', (ctypes.structure,), {}) dummy_type = type('dummy_type', (struct_dummy_struct,), {}) official_type = type('official_type', (dummy_type,), {}) struct_dummy_struct._fields_ = [('another_struct', ctypes.pointer(official_type))]
of course, not possible:
traceback (most recent call last): file "<stdin>", line 1, in <module> attributeerror: _fields_ final
i think i'm trying theoretically impossible, given way ctypes
works, if tell me there's way, delighted!
you not need same construction in python:
class official_type(ctypes.structure): pass official_type._fields_ = [("another_struct", ctypes.pointer(official_type))] first_instance = official_type() second_instance = official_type() first_instance.another_struct = ctypes.pointer(second_instance) print first_instance.another_struct
<__main__.lp_official_type object @ ...>
ctypes has funky struct finalization process, if dig unit tests you'll find like:
structure/union classes must 'finalized' sooner or later, when 1 of these things happen:
- _fields_ set.
- an instance created.
- the type used field of structure/union.
- the type subclassed
when finalized, assigning fields no longer allowed.
perhaps class definition using type messes process up.
Comments
Post a Comment