Struct pyo3::types::capsule::PyCapsule

source ·
#[repr(transparent)]
pub struct PyCapsule(PyAny);
Expand description

Represents a Python Capsule as described in Capsules:

This subtype of PyObject represents an opaque value, useful for C extension modules who need to pass an opaque value (as a void* pointer) through Python code to other C code. It is often used to make a C function pointer defined in one module available to other modules, so the regular import mechanism can be used to access C APIs defined in dynamically loaded modules.

§Example

use pyo3::{prelude::*, types::PyCapsule};
use std::ffi::CString;

#[repr(C)]
struct Foo {
    pub val: u32,
}

let r = Python::with_gil(|py| -> PyResult<()> {
    let foo = Foo { val: 123 };
    let name = CString::new("builtins.capsule").unwrap();

    let capsule = PyCapsule::new_bound(py, foo, Some(name.clone()))?;

    let module = PyModule::import_bound(py, "builtins")?;
    module.add("capsule", capsule)?;

    let cap: &Foo = unsafe { PyCapsule::import(py, name.as_ref())? };
    assert_eq!(cap.val, 123);
    Ok(())
});
assert!(r.is_ok());

Tuple Fields§

§0: PyAny

Implementations§

source§

impl PyCapsule

source

#[doc(hidden)] pub const _PYO3_DEF: AddTypeToModule<Self> = _

source§

impl PyCapsule

source

pub fn new_bound<T: 'static + Send + AssertNotZeroSized>( py: Python<'_>, value: T, name: Option<CString> ) -> PyResult<Bound<'_, Self>>

Constructs a new capsule whose contents are value, associated with name. name is the identifier for the capsule; if it is stored as an attribute of a module, the name should be in the format "modulename.attribute".

It is checked at compile time that the type T is not zero-sized. Rust function items need to be cast to a function pointer (fn(args) -> result) to be put into a capsule.

§Example
use pyo3::{prelude::*, types::PyCapsule};
use std::ffi::CString;

Python::with_gil(|py| {
    let name = CString::new("foo").unwrap();
    let capsule = PyCapsule::new_bound(py, 123_u32, Some(name)).unwrap();
    let val = unsafe { capsule.reference::<u32>() };
    assert_eq!(*val, 123);
});

However, attempting to construct a PyCapsule with a zero-sized type will not compile:

use pyo3::{prelude::*, types::PyCapsule};
use std::ffi::CString;

Python::with_gil(|py| {
    let capsule = PyCapsule::new_bound(py, (), None).unwrap();  // Oops! `()` is zero sized!
});
source

pub fn new_bound_with_destructor<T: 'static + Send + AssertNotZeroSized, F: FnOnce(T, *mut c_void) + Send>( py: Python<'_>, value: T, name: Option<CString>, destructor: F ) -> PyResult<Bound<'_, Self>>

Constructs a new capsule whose contents are value, associated with name.

Also provides a destructor: when the PyCapsule is destroyed, it will be passed the original object, as well as a *mut c_void which will point to the capsule’s context, if any.

The destructor must be Send, because there is no guarantee which thread it will eventually be called from.

source

pub unsafe fn import<'py, T>(py: Python<'py>, name: &CStr) -> PyResult<&'py T>

Imports an existing capsule.

The name should match the path to the module attribute exactly in the form of "module.attribute", which should be the same as the name within the capsule.

§Safety

It must be known that the capsule imported by name contains an item of type T.

Methods from Deref<Target = PyAny>§

source

#[doc(hidden)] pub const _PYO3_DEF: AddTypeToModule<Self> = _

Trait Implementations§

source§

impl AsPyPointer for PyCapsule

source§

fn as_ptr(&self) -> *mut PyObject

Gets the underlying FFI pointer, returns a borrowed pointer.

source§

impl AsRef<PyAny> for PyCapsule

source§

fn as_ref(&self) -> &PyAny

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl Deref for PyCapsule

§

type Target = PyAny

The resulting type after dereferencing.
source§

fn deref(&self) -> &PyAny

Dereferences the value.
source§

impl PyTypeInfo for PyCapsule

source§

const NAME: &'static str = "PyCapsule"

Available on non-crate feature gil-refs only.
Class name.
source§

const MODULE: Option<&'static str> = _

Available on non-crate feature gil-refs only.
Module name, if any.
source§

fn type_object_raw(py: Python<'_>) -> *mut PyTypeObject

Available on non-crate feature gil-refs only.
Returns the PyTypeObject instance for this type.
source§

fn is_type_of_bound(obj: &Bound<'_, PyAny>) -> bool

Available on non-crate feature gil-refs only.
Checks if object is an instance of this type or a subclass of this type.
source§

fn type_object_bound(py: Python<'_>) -> Bound<'_, PyType>

Available on non-crate feature gil-refs only.
Returns the safe abstraction over the type object.
source§

fn is_exact_type_of_bound(object: &Bound<'_, PyAny>) -> bool

Available on non-crate feature gil-refs only.
Checks if object is an instance of this type.
source§

impl DerefToPyAny for PyCapsule

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> AssertNotZeroSized for T

source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> IntoEither for T

source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

impl<T> PyTypeCheck for T
where T: PyTypeInfo,

source§

const NAME: &'static str = const NAME: &'static str = <T as PyTypeInfo>::NAME;

Available on non-crate feature gil-refs only.
Name of self. This is used in error messages, for example.
source§

fn type_check(object: &Bound<'_, PyAny>) -> bool

Available on non-crate feature gil-refs only.
Checks if object is an instance of Self, which may include a subtype. Read more
source§

impl<T> SizedTypeProperties for T

source§

#[doc(hidden)] const IS_ZST: bool = _

🔬This is a nightly-only experimental API. (sized_type_properties)
true if this type requires no storage. false if its size is greater than zero. Read more
source§

impl<T> SomeWrap<T> for T

source§

fn wrap(self) -> Option<T>

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
⚠️ Internal Docs ⚠️ Not Public API 👉 Official Docs Here