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
分支
36k
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 摘要。