python / python/cpython

ctypes._CData._b_base_ does not point to root ctypes object

未关闭
#135,669 0 条评论 1 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

docs topic-ctypes
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

Hi, I've been writing some binary interface "decoder" in python using ctypes, and one thing confuses me a bit (and also ruins some of my expectations)

The docs say:

The _b_base_ read-only member is the root ctypes object that owns the memory block.

So with this code:

import ctypes

bindata = bytearray(b"AAAABBBBCCCC")

SomeArray = ctypes.c_int * 3
class SomeData(ctypes.Structure):
    _fields_ = [
        ("asdf", SomeArray),
    ]

class FinalData(ctypes.Structure):
    _fields_ = [
        ("foo", SomeData),
    ]

x = FinalData.from_buffer(bindata)
print(x)
print(hex(ctypes.addressof(x)))
print(x._b_base_)
print()

foo = x.foo
print(foo)
print(hex(ctypes.addressof(foo)))
print(foo._b_base_)
print()

asdf = foo.asdf
print(asdf)
print(hex(ctypes.addressof(asdf)))
print(asdf._b_base_)
print()

I expect foo._b_base_ and asdf._b_base_ to point to the same FinalData object, meanwhile this is the output:

<__main__.FinalData object at 0x7f3bae3fa5d0>
0x7f3bae6985d0
None

<__main__.SomeData object at 0x7f3bae6597b0>
0x7f3bae6985d0
<__main__.FinalData object at 0x7f3bae3fa5d0>

<__main__.c_int_Array_3 object at 0x7f3bae69e450>
0x7f3bae6985d0
<__main__.SomeData object at 0x7f3bae6597b0>

So instead of root ctypes object, this returns the parent ctypes object. Is this an oversight/bug?

Python version: Python 3.14.0b2
OS: NixOS unstable

Linked PRs
  • gh-152623
  • gh-152706

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

先阅读 ctypes._CData.b_base 文档并运行提供的 reproducer。跟踪 FinalData、SomeData 和 SomeArray 的父链,然后将链接的 PRs 作为上下文;当文档所述的 root-owner 行为和回归覆盖与预期语义一致时,即表示完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
backend
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
25/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。