Skip to content

Commit 2bb1026

Browse files
committed
Fix ctypes subclass bitfields and native type metadata
Assisted-by: Codex:GPT-6
1 parent b811715 commit 2bb1026

3 files changed

Lines changed: 56 additions & 32 deletions

File tree

‎crates/vm/src/stdlib/_ctypes/base.rs‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1875,7 +1875,12 @@ impl GetDescriptor for PyCField {
18751875
// Get PyCData from obj (works for both Structure and Union)
18761876
let cdata = Self::get_cdata_from_obj(&obj, vm)?;
18771877

1878-
if zelf.bitfield_size > 0 && zelf.proto.stg_info(vm)?.scalar_code != Some('?') {
1878+
// CPython's c_bool bitfields read the whole byte. User scalar subclasses
1879+
// return storage-backed instances rather than decoded primitive values.
1880+
if zelf.bitfield_size > 0
1881+
&& super::simple::returns_scalar(&zelf.proto)
1882+
&& zelf.proto.stg_info(vm)?.scalar_code != Some('?')
1883+
{
18791884
let buffer = cdata.buffer.read();
18801885
let data = buffer
18811886
.get(offset..offset.saturating_add(size))
@@ -1974,6 +1979,7 @@ impl Py<PyCField> {
19741979
let needs_swap = super::simple::is_swapped(&zelf.proto) && size > 1;
19751980

19761981
let code = zelf.proto.stg_info(vm)?.scalar_code;
1982+
// Match CPython: c_bool writes the whole byte, even for bitfields.
19771983
if zelf.bitfield_size > 0 && code != Some('?') {
19781984
let code = code.ok_or_else(|| vm.new_type_error("invalid bitfield type"))?;
19791985
let mut encoded = [0; 4];

‎crates/vm/src/stdlib/_ctypes/function.rs‎

Lines changed: 14 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -261,16 +261,10 @@ impl ArgumentType for PyTypeRef {
261261
{
262262
None
263263
} else {
264-
// Use get_attr to traverse MRO (for subclasses like MyInt(c_int))
264+
// Converters belong to initialized storage, not mutable _type_.
265265
let typ = self
266-
.as_object()
267-
.get_attr(vm.ctx.intern_str("_type_"), vm)
268-
.ok()
266+
.type_code(vm)
269267
.ok_or_else(|| vm.new_type_error("Unsupported argument type"))?;
270-
let typ = typ
271-
.downcast_ref::<PyStr>()
272-
.ok_or_else(|| vm.new_type_error("Unsupported argument type"))?
273-
.to_string();
274268
if ffi_type_from_code(&typ).is_none() {
275269
return Err(vm.new_type_error(format!("Unsupported argument type: {typ}")));
276270
}
@@ -643,16 +637,12 @@ fn cast_check_pointertype(ctype: &PyObject, vm: &VirtualMachine) -> bool {
643637
return true;
644638
}
645639

646-
// simple pointer types via StgInfo.proto (c_void_p, c_char_p, etc.)
647-
if let Ok(type_attr) = ctype.get_attr("_type_", vm)
648-
&& let Some(s) = type_attr.downcast_ref::<PyStr>()
640+
// Simple pointer types retain the representation selected at creation,
641+
// even if the user later changes the Python-visible _type_ attribute.
642+
if let Some(ty) = ctype.downcast_ref::<PyType>()
643+
&& let Some(code) = ty.type_code(vm)
649644
{
650-
let c = s
651-
.to_str()
652-
.expect("_type_ is validated as ASCII at type creation");
653-
if c.len() == 1 && "sPzUZXO".contains(c) {
654-
return true;
655-
}
645+
return code.len() == 1 && "sPzUZXO".contains(code.as_str());
656646
}
657647

658648
false
@@ -1119,15 +1109,12 @@ fn compute_ret_spec(
11191109
return RetSpec::Pointer;
11201110
}
11211111

1122-
// Simple type via its _type_ code (traversing MRO)
1123-
if let Ok(type_attr) = restype_type
1124-
.as_object()
1125-
.get_attr(vm.ctx.intern_str("_type_"), vm)
1126-
&& let Some(s) = type_attr.downcast_ref::<PyStr>()
1127-
&& let Some(code) = s.to_str()
1128-
&& ffi_type_from_code(code).is_some()
1112+
// Simple type via its initialized scalar converter.
1113+
if let Some(code) = restype_type
1114+
.type_code(vm)
1115+
.filter(|code| ffi_type_from_code(code).is_some())
11291116
{
1130-
return if simple_type_is_pointer(code) {
1117+
return if simple_type_is_pointer(&code) {
11311118
RetSpec::Pointer
11321119
} else {
11331120
RetSpec::Code(code.chars().next().unwrap_or('i'))
@@ -1605,15 +1592,11 @@ fn convert_raw_result(
16051592
// finalize it), which would self-deadlock against a held read guard.
16061593
let is_pointer_type = info.flags.contains(StgInfoFlags::TYPEFLAG_ISPOINTER);
16071594
let has_proto = info.proto.is_some();
1595+
let scalar_code = info.scalar_code;
16081596
drop(info);
16091597

16101598
// py_object: interpret return value as PyObject* and materialize it.
1611-
if let Ok(type_attr) = restype_type
1612-
.as_object()
1613-
.get_attr(vm.ctx.intern_str("_type_"), vm)
1614-
&& let Some(type_str) = type_attr.downcast_ref::<PyStr>()
1615-
&& type_str.to_str() == Some("O")
1616-
{
1599+
if scalar_code == Some('O') {
16171600
let ptr = NonNull::new(result_word as *mut PyObject)
16181601
.ok_or_else(|| vm.new_value_error("PyObject is NULL"))?;
16191602
unsafe {

‎extra_tests/snippets/stdlib_ctypes.py‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -972,6 +972,41 @@ class MutableInt(ctypes.c_int):
972972
assert _array[0].value == -2
973973
assert MutableInt(-3).value == -3
974974

975+
# Native calls must use the same initialized converter for arguments and results.
976+
MutableInt._type_ = "h"
977+
_identity = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int)(lambda value: value)
978+
_identity.argtypes = [MutableInt]
979+
assert _identity(MutableInt(-65537)) == -65537
980+
_identity.argtypes = [ctypes.c_int]
981+
_identity.restype = MutableInt
982+
_result = _identity(-65537)
983+
assert getattr(_result, "value", _result) == -65537
984+
985+
986+
class MutablePointer(ctypes.c_void_p):
987+
pass
988+
989+
990+
MutablePointer._type_ = "i"
991+
assert ctypes.cast(ctypes.c_void_p(123), MutablePointer).value == 123
992+
MutableInt._type_ = "P"
993+
try:
994+
ctypes.cast(ctypes.c_void_p(123), MutableInt)
995+
except TypeError:
996+
pass
997+
else:
998+
raise AssertionError("cast accepted a scalar integer type")
999+
1000+
1001+
class SubclassBits(ctypes.Structure):
1002+
_fields_ = [("field", MutableInt, 3)]
1003+
1004+
1005+
_bits = SubclassBits(3)
1006+
assert isinstance(_bits.field, MutableInt)
1007+
_bits.field.value = 2
1008+
assert _bits.field.value == 2
1009+
9751010
for _scalar, _text_value in ((ctypes.c_char, b"ab"), (ctypes.c_wchar, "ab")):
9761011

9771012
class MutableChar(_scalar):

0 commit comments

Comments
 (0)