访问xrange内部结构

发布于 2024-08-12 11:52:18 字数 239 浏览 3 评论 0原文

我正在尝试使用 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 技术交流群。

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

发布评论

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

评论(2

任性一次 2024-08-19 11:52:18

您可以在没有 ctypes 的情况下访问所需的数据:

>>> obj = xrange(1,11,2)
>>> obj.__reduce__()[1]
(1, 11, 2)
>>> len(obj)
5

请注意,__reduce__() 方法正是用于序列化。请阅读文档中的本章了解更多信息。

更新:但请确保您也可以使用ctypes访问内部数据:

from ctypes import *

PyObject_HEAD = [
    ('ob_refcnt', c_size_t),
    ('ob_type', c_void_p),
]

class XRangeType(Structure):
    _fields_ = PyObject_HEAD + [
        ('start', c_long),
        ('step', c_long),
        ('len', c_long),
    ]

range_obj = xrange(1, 11, 2)

c_range_obj = cast(c_void_p(id(range_obj)), POINTER(XRangeType)).contents
print c_range_obj.start, c_range_obj.step, c_range_obj.len

You can access data you need without ctypes:

>>> obj = xrange(1,11,2)
>>> obj.__reduce__()[1]
(1, 11, 2)
>>> len(obj)
5

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:

from ctypes import *

PyObject_HEAD = [
    ('ob_refcnt', c_size_t),
    ('ob_type', c_void_p),
]

class XRangeType(Structure):
    _fields_ = PyObject_HEAD + [
        ('start', c_long),
        ('step', c_long),
        ('len', c_long),
    ]

range_obj = xrange(1, 11, 2)

c_range_obj = cast(c_void_p(id(range_obj)), POINTER(XRangeType)).contents
print c_range_obj.start, c_range_obj.step, c_range_obj.len
玩心态 2024-08-19 11:52:18

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.

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