python / python/cpython

ctypes._CData.from_buffer does not inherit _b_base_

未關閉
#135,894 1 則留言 1 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

docs topic-ctypes
主要語言
Python
星號
77.2k
分支
35.9k
PR 合併指標
PR 指標待擷取

描述

Continuing work from #135669, I have noticed another inconsistency.

from_buffer docs say:

This method returns a ctypes instance that shares the buffer of the source object.

_b_base_ docs say:

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

So, I assumed that, when passing a ctypes object as source to from_buffer, the _b_base_ from the resulting ctypes object would be inherited from source, however that is not the case.

To better visualize the issue, lets consider this code:

import ctypes

bindata = bytearray([
    0, 0, # [0].offset
    2, 0, # [0].variant
    8, 0, # [1].offset
    1, 0, # [1].variant

    # dynamic_part
    1, 2, 3, 4,
    5, 6,

    0, 0,

    9, 8, 7, 6,
])

class A(ctypes.Structure):
    _fields_ = [
        ("foo", ctypes.c_int),
    ]
class B(ctypes.Structure):
    _fields_ = [
        ("bar", ctypes.c_byte * 6),
    ]

class Message(ctypes.Structure):
    _fields_ = [
        ("offset", ctypes.c_uint16),
        ("variant", ctypes.c_uint16),
    ]

    variants = {
        1: A,
        2: B,
    }

    def get(self):
        root = self._b_base_._b_base_
        _type = self.variants[self.variant]

        try:
            return _type.from_buffer(root.dynamic_part, self.offset)
        except ValueError as e:
            e.add_note(f"Invalid data offset={self.offset} variant={self.variant}")
            raise

class FinalData(ctypes.Structure):
    _fields_ = [
        ("messages", Message * 2),
        ("dynamic_part", ctypes.c_ubyte * 12),
    ]

x = FinalData.from_buffer(bindata)

print(x)
print(x.dynamic_part._b_base_)

a = x.messages[1].get()
b = x.messages[0].get()
print(a)
print(a._b_base_)
print(b)
print(b._b_base_)

I expected the a._b_base_ and b._b_base_ would be <__main__.FinalData object at 0x7fbee293d3d0>, like x.dynamic_part._b_base_, instead it is None.

Linked PRs
  • gh-152706

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

先檢查連結的 PR gh-152706,並執行提供的 ctypes 重現程式。接著檢查 _CData.from_buffer 背後的實作及其現有測試;當結果物件的 b_base 所有權鏈符合文件所述的緩衝區所有權行為時,即視為完成。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
python
領域
backend
Issue 類型
缺陷
難度
4/5
預估耗時
3-5 天
活躍度
停滯
描述清晰度
描述清楚
新手友好度
35/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。