如何创建指向正在定义的结构的指针?

发布于 2024-10-21 10:06:59 字数 956 浏览 2 评论 0原文

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

struct ifaddrs {
    struct ifaddrs *ifa_next;   /* Pointer to the next structure.  */
    ... /* SNIP!!11 */
};

但是,用 Python 表示:

class struct_ifaddrs(Structure):

    _fields_ = [
        ('ifa_next', POINTER(struct_ifaddrs)),]

给出此错误:

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

在类定义完成之前,struct_ifaddrs 将不会绑定到当前作用域。当然,作为指针类型,显然在声明时不需要像 C 那样定义 struct_ifaddrs ,但在以后使用时需要取消引用该类型。我该如何继续?

I'm writing a Python wrapper around getifaddrs(). The interface uses the struct ifaddrs type, the first field of which is a pointer to another struct ifaddrs.

struct ifaddrs {
    struct ifaddrs *ifa_next;   /* Pointer to the next structure.  */
    ... /* SNIP!!11 */
};

However, representing this in Python:

class struct_ifaddrs(Structure):

    _fields_ = [
        ('ifa_next', POINTER(struct_ifaddrs)),]

Gives this error:

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

struct_ifaddrs will not be bound to the current scope until the class definition is completed. Of course being a pointer type, it's obvious that the definition of struct_ifaddrs isn't required during declaration just as in C, but the type needs to be deref'd during later use. How can I proceed?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无人接听 2024-10-28 10:06:59

这个怎么样?

class struct_ifaddrs(Structure):
    pass
struct_ifaddrs._fields_ = [
    ('ifa_next', POINTER(struct_ifaddrs)),]

正如 Paul McGuire 在评论中指出的那样,这在 ctypes 文档同一文档中的另一次

How about this?

class struct_ifaddrs(Structure):
    pass
struct_ifaddrs._fields_ = [
    ('ifa_next', POINTER(struct_ifaddrs)),]

As Paul McGuire notes in the comments, this is documented as standard solution for this problem in the ctypes documentation and yet another time in the same docs.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文