Add memoryview support to c-api (#8240)

This commit is contained in:
Bas Schoenmaeckers authored and GitHub committed 2026-07-09 14:12:10 +09:00
1 parent 6b1bd401d0
commit bf98131551
2 files changed
+38

No files matched your search

+1
View File
@@ -22,6 +22,7 @@ pub mod genericaliasobject;
pub mod import;
pub mod listobject;
pub mod longobject;
pub mod memoryobject;
pub mod methodobject;
pub mod moduleobject;
pub mod object;
+37
View File
@@ -0,0 +1,37 @@
use crate::object::define_py_check;
use crate::{PyObject, pystate::with_vm};
use rustpython_vm::PyPayload;
use rustpython_vm::builtins::PyMemoryView;
define_py_check!(fn PyMemoryView_Check, types.memoryview_type);
#[unsafe(no_mangle)]
pub unsafe extern "C" fn PyMemoryView_FromObject(obj: *mut PyObject) -> *mut PyObject {
with_vm(|vm| {
let obj = unsafe { &*obj };
Ok(PyMemoryView::from_object(obj, vm)?.into_ref(&vm.ctx))
})
}
#[cfg(test)]
mod tests {
use pyo3::prelude::*;
use pyo3::types::{PyBytes, PyMemoryView};
#[test]
fn memoryview_from_bytes() {
Python::attach(|py| {
let bytes = PyBytes::new(py, b"hello");
let view = PyMemoryView::from(&bytes).unwrap();
assert!(view.is_instance_of::<PyMemoryView>());
let copied = view
.call_method1("tobytes", ())
.unwrap()
.cast_into::<PyBytes>()
.unwrap();
assert_eq!(copied.as_bytes(), b"hello");
})
}
}