如何为定义的结构创建指针?

Mat*_*ner 2 python ctypes pointers structure linked-list

我正在写一个Python包装器getifaddrs().接口使用struct ifaddrs类型,其第一个字段是指向另一个的指针struct ifaddrs.

struct ifaddrs {
    struct ifaddrs *ifa_next;   /* Pointer to the next structure.  */
    ... /* SNIP!!11 */
};
Run Code Online (Sandbox Code Playgroud)

但是,在Python中表示这一点:

class struct_ifaddrs(Structure):

    _fields_ = [
        ('ifa_next', POINTER(struct_ifaddrs)),]
Run Code Online (Sandbox Code Playgroud)

给出了这个错误:

matt@stanley:~/src/pydlnadms$ ./getifaddrs.py 
Traceback (most recent call last):
  File "./getifaddrs.py", line 58, in <module>
    class struct_ifaddrs(Structure):
  File "./getifaddrs.py", line 61, in struct_ifaddrs
    ('ifa_next', POINTER(struct_ifaddrs)),
NameError: name 'struct_ifaddrs' is not defined
Run Code Online (Sandbox Code Playgroud)

struct_ifaddrs在类定义完成之前,不会绑定到当前作用域.当然是一个指针类型,显然struct_ifaddrs在声明过程中不需要定义,就像在C中一样,但是在以后的使用过程中需要解析类型.我该怎么办?

Sve*_*ach 5

这个怎么样?

class struct_ifaddrs(Structure):
    pass
struct_ifaddrs._fields_ = [
    ('ifa_next', POINTER(struct_ifaddrs)),]
Run Code Online (Sandbox Code Playgroud)

正如Paul McGuire在评论中指出的那样,这在ctypes文档中被记录为此问题的标准解决方案,而在同一文档中则是另一次.