如何通过ctypes在python中对包含对其定义的引用的结构进行建模? [英] How to model struct that contains reference to it's definition in python through ctypes?
问题描述
试图将引用的结构包装如下
trying to wrap struct the reference it's definition as below
foo.c
foo.c
typedef struct Foo {
struct Foo *foo;
} Foo;
如何建模,例如
foo.py
foo.py
class Foo(Structure):
_fields_ = [('foo', pointer(Foo))]
当然,Python不会不能这样解释,我可以使用c_void_p代替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
但是,有没有一种方法可以在python类中对结构进行建模?
but, is there a way to model that struct in a python class?
推荐答案
来自< a href = https://docs.python.org/3/library/ctypes.html#incomplete-types rel = nofollow noreferrer> [Python]:类型不完整:
...。在 ctypes 中,我们可以定义
cell
类,然后在类语句之后设置_fields _
属性。
... . In ctypes, we can define the
cell
class and and set the_fields_
attribute later, after the class statement.
如果我们将其应用于当前问题,则代码看起来像这样:
If we apply that to the current problem, the code would look smth like:
from ctypes import Structure, POINTER
class Foo(Structure):
pass
Foo._fields_ = [
("foo_ptr", POINTER(Foo)),
]
这篇关于如何通过ctypes在python中对包含对其定义的引用的结构进行建模?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!