ctypes: subclassed swapped endianness doesn't swap
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 77.2k
- Forks
- 36k
- PR merge metrics
- PR metrics pending
Description
Bug report
Subclassing a swapped simple type and calling from_buffer_copy doesn't swap bytes. Here is a minimal non-working example.
import ctypes
cshort_be = ctypes.c_ushort.__ctype_be__
class Short(cshort_be):
pass
print(cshort_be.from_buffer_copy(b"\x00\x01").value) # prints 1
print(Short.from_buffer_copy(b"\x00\x01").value) # prints 256
However, there is a simple workaround:
print(Short.__ctype_be__.from_buffer_copy(b"\x00\x01").value) # prints 1
I am not sure what happens, but ctypes behave kinda weird when subclassing native types. So this bug might be related to issue #73456.
My environment
- CPython versions tested on: 3.10.5
- Operating system and architecture:
Linux Celap 5.18.0-1-amd64 #1 SMP PREEMPT_DYNAMIC Debian 5.18.2-1 (2022-06-06) x86_64 GNU/Linux
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the minimal ctypes example using c_ushort.ctype_be and a subclass, then compare the from_buffer_copy behavior of the base swapped type and subclass. Trace the ctypes handling of swapped simple types and determine how the subclass path differs; done means the subclass produces the same byte-swapped value as the base type and the regression is covered by a test.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- backend
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 35/100