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§


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.


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.

use std::sync::mpsc::{channel, Sender};
use libc::c_void;
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_bound_with_destructor(py, 123, None, destructor as fn(u32, *mut c_void))
    let context = Box::new(tx);  // `Sender<String>` is our context, box it up and ship it!
    // This scope will end, causing our destructor to be called...

assert_eq!(rx.recv(), Ok("Destructor called!".to_string()));

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.


unsafe fn reference<T>(&self) -> &'py T

Obtains a reference to the value of this capsule.


It must be known that this capsule is valid and its pointer is to an item of type T.


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.


fn is_valid(&self) -> bool

Checks if this is a valid capsule.

Returns true if the stored pointer() is non-null.


fn name(&self) -> PyResult<Option<&'py CStr>>

Retrieves the name of this capsule, if set.

Returns an error if this capsule is not valid.

Object Safety§

This trait is not object safe.



impl<'py> PyCapsuleMethods<'py> for Bound<'py, PyCapsule>