How to model struct that contains reference to it's definition in python through ctypes?

Question:

trying to wrap struct the reference it’s definition as below

foo.c

typedef struct Foo {
  struct Foo *foo;
} Foo;

how to model that, for example

foo.py

class Foo(Structure):
    _fields_ = [('foo', pointer(Foo))]

of course python doesn’t interpret that, I could use c_void_p instead of pointer(Foo), and cast it’s value as follow

F = clib.get_foo()
cast(F.foo, pointer(Foo)) #although i'm not sure if it would work

but, is there a way to model that struct in a python class?

Asked By: Error

||

Answers:

From [Python.Docs]: ctypes – Incomplete Types:

… . In ctypes, we can define the cell class and and set the _fields_ attribute later, after the class statement.

Applying that to the current problem, the code would look smth like:

import ctypes as ct


class Foo(ct.Structure):
    pass

Foo._fields_ = (
    ("foo_ptr", ct.POINTER(Foo)),
)
Answered By: CristiFati
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.