pyo3::conversion

Trait AsPyPointer

source
pub unsafe trait AsPyPointer {
    // Required method
    fn as_ptr(&self) -> *mut PyObject;
}
Expand description

Returns a borrowed pointer to a Python object.

The returned pointer will be valid for as long as self is. It may be null depending on the implementation.

§Examples

use pyo3::prelude::*;
use pyo3::types::PyString;
use pyo3::ffi;

Python::with_gil(|py| {
    let s: Py<PyString> = "foo".into_py(py);
    let ptr = s.as_ptr();

    let is_really_a_pystring = unsafe { ffi::PyUnicode_CheckExact(ptr) };
    assert_eq!(is_really_a_pystring, 1);
});

§Safety

For callers, it is your responsibility to make sure that the underlying Python object is not dropped too early. For example, the following code will cause undefined behavior:

Python::with_gil(|py| {
    let ptr: *mut ffi::PyObject = 0xabad1dea_u32.into_py(py).as_ptr();

    let isnt_a_pystring = unsafe {
        // `ptr` is dangling, this is UB
        ffi::PyUnicode_CheckExact(ptr)
    };
});

This happens because the pointer returned by as_ptr does not carry any lifetime information and the Python object is dropped immediately after the 0xabad1dea_u32.into_py(py).as_ptr() expression is evaluated. To fix the problem, bind Python object to a local variable like earlier to keep the Python object alive until the end of its scope.

Implementors must ensure this returns a valid pointer to a Python object, which borrows a reference count from &self.

Required Methods§

source

fn as_ptr(&self) -> *mut PyObject

Returns the underlying FFI pointer as a borrowed pointer.

Implementations on Foreign Types§

source§

impl<T> AsPyPointer for Option<T>
where T: AsPyPointer,

Convert None into a null pointer.

Implementors§

source§

impl<T> AsPyPointer for Bound<'_, T>

source§

impl<T> AsPyPointer for Py<T>

source§

impl<T: PyClass> AsPyPointer for PyRef<'_, T>