pyo3/types/
memoryview.rs

1use crate::err::PyResult;
2use crate::ffi_ptr_ext::FfiPtrExt;
3use crate::py_result_ext::PyResultExt;
4use crate::{ffi, Bound, PyAny};
5
6/// Represents a Python `memoryview`.
7///
8/// Values of this type are accessed via PyO3's smart pointers, e.g. as
9/// [`Py<PyMemoryView>`][crate::Py] or [`Bound<'py, PyMemoryView>`][Bound].
10#[repr(transparent)]
11pub struct PyMemoryView(PyAny);
12
13pyobject_native_type_core!(PyMemoryView, pyobject_native_static_type_object!(ffi::PyMemoryView_Type), #checkfunction=ffi::PyMemoryView_Check);
14
15impl PyMemoryView {
16    /// Creates a new Python `memoryview` object from another Python object that
17    /// implements the buffer protocol.
18    pub fn from<'py>(src: &Bound<'py, PyAny>) -> PyResult<Bound<'py, Self>> {
19        unsafe {
20            ffi::PyMemoryView_FromObject(src.as_ptr())
21                .assume_owned_or_err(src.py())
22                .downcast_into_unchecked()
23        }
24    }
25
26    /// Deprecated name for [`PyMemoryView::from`].
27    #[deprecated(since = "0.23.0", note = "renamed to `PyMemoryView::from`")]
28    #[inline]
29    pub fn from_bound<'py>(src: &Bound<'py, PyAny>) -> PyResult<Bound<'py, Self>> {
30        Self::from(src)
31    }
32}
33
34impl<'py> TryFrom<&Bound<'py, PyAny>> for Bound<'py, PyMemoryView> {
35    type Error = crate::PyErr;
36
37    /// Creates a new Python `memoryview` object from another Python object that
38    /// implements the buffer protocol.
39    fn try_from(value: &Bound<'py, PyAny>) -> Result<Self, Self::Error> {
40        PyMemoryView::from(value)
41    }
42}