访问xrange内部结构
我正在尝试使用 ctypes 从内部 python 结构中提取数据。也就是说,我正在尝试读取 xrange 中的 4 个字段:
typedef struct {
PyObject_HEAD
long start;
long step;
long len;
} rangeobject;
是否有任何标准方法可以在 python 本身中获取这些字段?
I'm trying to use ctypes to extract data from internal python structures. Namely, I'm trying to read the 4 fields in an xrange:
typedef struct {
PyObject_HEAD
long start;
long step;
long len;
} rangeobject;
Is there any standard way of getting at such fields within python itself?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在没有
ctypes
的情况下访问所需的数据:请注意,
__reduce__()
方法正是用于序列化。请阅读文档中的本章了解更多信息。更新:但请确保您也可以使用
ctypes
访问内部数据:You can access data you need without
ctypes
:Note, that
__reduce__()
method is exactly for serialization. Read this chapter in documentation for more information.Update: But sure you can access internal data with
ctypes
too:ctypes 模块并不用于访问 Python 内部。 ctypes 允许您使用 C 术语处理 C 库,但使用 Python 进行编码。
您可能需要一个 C 扩展,它在很多方面与 ctypes 相反。使用 C 扩展,您可以用 Python 术语处理 Python 代码,但可以用 C 语言处理代码。
更新:既然您想要纯 Python,为什么需要访问内置 xrange 对象的内部结构? xrange 非常简单:用 Python 创建您自己的 xrange,然后用它做您想做的事情。
The ctypes module isn't meant for accessing Python internals. ctypes lets you deal with C libraries in C terms, but coding in Python.
You probably want a C extension, which in many ways is the opposite of ctypes. With a C extension, you deal with Python code in Python terms, but code in C.
UPDATED: Since you want pure Python, why do you need to access the internals of a built-in xrange object? xrange is very simple: create your own in Python, and do what you want with it.