如何创建指向正在定义的结构的指针?
我正在围绕 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技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个怎么样?
正如 Paul McGuire 在评论中指出的那样,这在 ctypes 文档 和同一文档中的另一次。
How about this?
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.