如何在ctypes中设置指向自身的结构?

2024-10-06 07:17:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下结构的C声明:

struct vnode {
   char firstchar;
   uint8_t wordlength;

   bool is_red;

   struct vnode *left;
   struct vnode *right;
   struct textelem *texts;
};

非常典型的树,有一些有效载荷。我试图将此重写为以下ctypes声明:

^{pr2}$

不幸的是,这不起作用,因为那时python编译器还不知道类型VNODE。在

所以我把它重写到下面的类中:

class VNODE(Structure):
    def __init__(self):
        self._fields_ = [("firstchar", c_char),
                ("wordlength", c_ubyte),
                ("is_red", c_bool),
                ("left", POINTER(VNODE)),
                ("right", POINTER(VNODE)),
                ("textelem", POINTER(TEXTELEM))]

这不起作用,因为现在ctypes无法推断正确的构造函数(我已经用1个参数编写了它),也无法推断正确的getter。所以我得到了下面两个错误中的一个

TypeError: __init__() takes 1 positional argument but 7 were given
AttributeError: 'LP_VNODE' object has no attribute 'firstchar

最后,我提出了以下工作解决方案,但由于指针类型现在是未编码的,我不确定这是否是正确的方法:

class VNODE(Structure):
    _fields_ = [("firstchar", c_char),         
                ("wordlength", c_ubyte),        
                ("is_red", c_bool),     
                ("left", c_void_p),
                ("right", c_void_p),
                ("textelem", POINTER(TEXTELEM))]

Tags: right声明isredctypesleftstructbool
1条回答
网友
1楼 · 发布于 2024-10-06 07:17:56

您可以模拟C风格的去公差,然后是定义。见ctypes docs on incomplete types

>>> class VNODE(Structure):  # incomplete type / forward declaration
...     pass
... 
>>> VNODE._fields_ = [("firstchar", c_char),
...                   ("wordlength", c_ubyte),
...                   ("is_red", c_bool),
...                   ("left", POINTER(VNODE)),
...                   ("right", POINTER(VNODE))]

相关问题 更多 >