Skip to content

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

Open
@Soveu

Description

@Soveu

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    Status

    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions