[New-bugs-announce] [issue32780] ctypes: memoryview gives incorrect PEP3118 format strings for both packed and unpacked structs

Eric Wieser report at bugs.python.org
Tue Feb 6 00:27:59 EST 2018


New submission from Eric Wieser <wieser.eric+pybug at gmail.com>:

Discovered [here](https://github.com/numpy/numpy/issues/10528)

Consider the following structure, and a memoryview created from it:

    class foo(ctypes.Structure):
        _fields_ = [('one', ctypes.c_uint8),
                    ('two', ctypes.c_uint32)]
    f = foo()
    mf = memoryview(f)

We'd expect this to insert padding, and it does:

>>> mf.itemsize
8

But that padding doesn't show up in the format string:

>>> mf.format
'T{<B:one:<I:two:}'

That format string describes the _packed_ version of the struct, with the `two` field starting at offset 1, based on the `struct` documentation on how `<` should be interpreted:

> No padding is added when using non-native size and alignment, e.g. with ‘<’, ‘>’

But ctypes doesn't even get it right for packed structs:


    class foop(ctypes.Structure):
        _fields_ = [('one', ctypes.c_uint8),
                    ('two', ctypes.c_uint32)]
        _pack_ = 1
    f = foo()
    mf = memoryview(f)

The size is what we'd expect:

>>> mf.itemsize
5

But the format is garbage:

>>> mf.format
'B'  # sizeof(byte) == 5!?

----------
components: ctypes
messages: 311705
nosy: Eric.Wieser
priority: normal
severity: normal
status: open
title: ctypes: memoryview gives incorrect PEP3118 format strings for both packed and unpacked structs
versions: Python 2.7, Python 3.4, Python 3.5, Python 3.6, Python 3.7, Python 3.8

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue32780>
_______________________________________


More information about the New-bugs-announce mailing list