python - 如何使用指向自身的指针在 ctypes 中设置结构?

标签 python ctypes

我有以下结构的 C 声明:

struct vnode {
   char firstchar;
   uint8_t wordlength;

   bool is_red;

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

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

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

不幸的是,这没有用,因为那时 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))]

最佳答案

您可以模仿 C 风格的decleration,然后是definition。见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))]

关于python - 如何使用指向自身的指针在 ctypes 中设置结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30423835/

相关文章:

python - 如何将非硬编码参数传递给Python装饰器?

c - Python调用C语言时,返回值异常

python - 与 python 中长时间运行的任务通信

加载库时Python ctypes错误GOMP_ritic_end

javascript - 检查用户是否登录时 Django 模板错误

python - 在python中按索引绘制字符串数据

python - Python中的串行向量减法或 "subtractive convolution"?

python - 为什么 ctypes 将 Python 列表转换为 C 数组的速度如此之慢?

Python:将 ip 地址打包为 ctype.c_ulong() 以便与 DLL 一起使用

python - 关于如何在 Keras 中构建 CNN 1D 的正确而明确的解释