Skip to content

Commit b5be40e

Browse files
Add memoryview support to c-api
1 parent 6a118b3 commit b5be40e

2 files changed

Lines changed: 38 additions & 0 deletions

File tree

crates/capi/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ pub mod genericaliasobject;
2222
pub mod import;
2323
pub mod listobject;
2424
pub mod longobject;
25+
pub mod memoryobject;
2526
pub mod methodobject;
2627
pub mod moduleobject;
2728
pub mod object;

crates/capi/src/memoryobject.rs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
use crate::object::define_py_check;
2+
use crate::{PyObject, pystate::with_vm};
3+
use rustpython_vm::PyPayload;
4+
use rustpython_vm::builtins::PyMemoryView;
5+
6+
define_py_check!(fn PyMemoryView_Check, types.memoryview_type);
7+
8+
#[unsafe(no_mangle)]
9+
pub unsafe extern "C" fn PyMemoryView_FromObject(obj: *mut PyObject) -> *mut PyObject {
10+
with_vm(|vm| {
11+
let obj = unsafe { &*obj };
12+
Ok(PyMemoryView::from_object(obj, vm)?.into_ref(&vm.ctx))
13+
})
14+
}
15+
16+
#[cfg(test)]
17+
mod tests {
18+
use pyo3::prelude::*;
19+
use pyo3::types::{PyBytes, PyMemoryView};
20+
21+
#[test]
22+
fn memoryview_from_bytes() {
23+
Python::attach(|py| {
24+
let bytes = PyBytes::new(py, b"hello");
25+
let view = PyMemoryView::from(&bytes).unwrap();
26+
27+
assert!(view.is_instance_of::<PyMemoryView>());
28+
29+
let copied = view
30+
.call_method1("tobytes", ())
31+
.unwrap()
32+
.cast_into::<PyBytes>()
33+
.unwrap();
34+
assert_eq!(copied.as_bytes(), b"hello");
35+
})
36+
}
37+
}

0 commit comments

Comments
 (0)