ctypes: subclassed swapped endianness doesn't swap

Open
#95,384 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
35/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Stale
Tech stack
python
Domain
backend

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.

Description

topic-ctypes type-bug

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
Dominant language
Python
Stars
77.2k
Forks
36k
Avg merge
1d 9h
Merged PRs (30d)
558

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from python/cpython

All issues in python/cpython

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.