pub trait PyCapsuleMethods<'py>: Sealed {
// Required methods
fn set_context(&self, context: *mut c_void) -> PyResult<()>;
fn context(&self) -> PyResult<*mut c_void>;
unsafe fn reference<T>(&self) -> &'py T;
fn pointer(&self) -> *mut c_void;
fn is_valid(&self) -> bool;
fn name(&self) -> PyResult<Option<&'py CStr>>;
}
Expand description
Implementation of functionality for PyCapsule
.
These methods are defined for the Bound<'py, PyCapsule>
smart pointer, so to use method call
syntax these methods are separated into a trait, because stable Rust does not yet support
arbitrary_self_types
.
Required Methods§
Sourcefn set_context(&self, context: *mut c_void) -> PyResult<()>
fn set_context(&self, context: *mut c_void) -> PyResult<()>
Sets the context pointer in the capsule.
Returns an error if this capsule is not valid.
§Notes
The context is treated much like the value of the capsule, but should likely act as a place to store any state management when using the capsule.
If you want to store a Rust value as the context, and drop it from the destructor, use
Box::into_raw
to convert it into a pointer, see the example.
§Example
use std::os::raw::c_void;
use std::sync::mpsc::{channel, Sender};
use pyo3::{prelude::*, types::PyCapsule};
let (tx, rx) = channel::<String>();
fn destructor(val: u32, context: *mut c_void) {
let ctx = unsafe { *Box::from_raw(context.cast::<Sender<String>>()) };
ctx.send("Destructor called!".to_string()).unwrap();
}
Python::with_gil(|py| {
let capsule =
PyCapsule::new_with_destructor(py, 123, None, destructor as fn(u32, *mut c_void))
.unwrap();
let context = Box::new(tx); // `Sender<String>` is our context, box it up and ship it!
capsule.set_context(Box::into_raw(context).cast()).unwrap();
// This scope will end, causing our destructor to be called...
});
assert_eq!(rx.recv(), Ok("Destructor called!".to_string()));
Sourcefn context(&self) -> PyResult<*mut c_void>
fn context(&self) -> PyResult<*mut c_void>
Gets the current context stored in the capsule. If there is no context, the pointer will be null.
Returns an error if this capsule is not valid.
Sourceunsafe fn reference<T>(&self) -> &'py T
unsafe fn reference<T>(&self) -> &'py T
Obtains a reference to the value of this capsule.
§Safety
It must be known that this capsule is valid and its pointer is to an item of type T
.
Sourcefn pointer(&self) -> *mut c_void
fn pointer(&self) -> *mut c_void
Gets the raw c_void
pointer to the value in this capsule.
Returns null if this capsule is not valid.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.