From 028b4c2c14c01d7370fb028741a7da1030724347 Mon Sep 17 00:00:00 2001 From: Bas Schoenmaeckers Date: Mon, 11 May 2026 17:08:26 +0200 Subject: [PATCH 1/2] Fix `ctypes.py_object` handling --- crates/vm/src/stdlib/_ctypes/base.rs | 14 ++++++++++++++ crates/vm/src/stdlib/_ctypes/simple.rs | 11 +++++++++++ 2 files changed, 25 insertions(+) diff --git a/crates/vm/src/stdlib/_ctypes/base.rs b/crates/vm/src/stdlib/_ctypes/base.rs index 7d611c27b0..2bbf7abccf 100644 --- a/crates/vm/src/stdlib/_ctypes/base.rs +++ b/crates/vm/src/stdlib/_ctypes/base.rs @@ -2342,6 +2342,20 @@ pub(super) fn bytes_to_pyobject( } Ok(vm.ctx.new_int(val).into()) } + "O" => { + // py_object: return Python object from pointer + let ptr = read_ptr_from_buffer(bytes); + if ptr == 0 { + return Err(vm.new_value_error("PyObject is NULL")); + } + let raw_ptr = ptr as *mut crate::object::PyObject; + unsafe { + let obj = + crate::PyObjectRef::from_raw(core::ptr::NonNull::new_unchecked(raw_ptr)); + let obj = core::mem::ManuallyDrop::new(obj); + Ok((*obj).clone()) + } + } "u" => { let val = if bytes.len() >= mem::size_of::() { let wc = if mem::size_of::() == 2 { diff --git a/crates/vm/src/stdlib/_ctypes/simple.rs b/crates/vm/src/stdlib/_ctypes/simple.rs index 1dd2001335..f5e07ebc2e 100644 --- a/crates/vm/src/stdlib/_ctypes/simple.rs +++ b/crates/vm/src/stdlib/_ctypes/simple.rs @@ -466,6 +466,17 @@ impl PyCSimpleType { } } } + // py_object: pass any Python object as PyObject* + Some("O") => { + return Ok(CArgObject { + tag: b'O', + value: FfiArgValue::Pointer(value.get_id()), + obj: value, + size: 0, + offset: 0, + } + .to_pyobject(vm)); + } // c_bool Some("?") => { let bool_val = value.is_true(vm)?; From 7639516f7315dcb0b1206da936574f5d672b3c70 Mon Sep 17 00:00:00 2001 From: Bas Schoenmaeckers Date: Mon, 11 May 2026 17:42:17 +0200 Subject: [PATCH 2/2] Assume owned pointer --- crates/vm/src/stdlib/_ctypes/base.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/crates/vm/src/stdlib/_ctypes/base.rs b/crates/vm/src/stdlib/_ctypes/base.rs index 2bbf7abccf..afc03213b2 100644 --- a/crates/vm/src/stdlib/_ctypes/base.rs +++ b/crates/vm/src/stdlib/_ctypes/base.rs @@ -2348,12 +2348,10 @@ pub(super) fn bytes_to_pyobject( if ptr == 0 { return Err(vm.new_value_error("PyObject is NULL")); } - let raw_ptr = ptr as *mut crate::object::PyObject; unsafe { let obj = - crate::PyObjectRef::from_raw(core::ptr::NonNull::new_unchecked(raw_ptr)); - let obj = core::mem::ManuallyDrop::new(obj); - Ok((*obj).clone()) + PyObjectRef::from_raw(core::ptr::NonNull::new_unchecked(ptr as *mut _)); + Ok(obj) } } "u" => {