我有以下结构的 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/