pub trait AsPyPointer {
    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::AsPyPointer;
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

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.

Required Methods

Returns the underlying FFI pointer as a borrowed pointer.

Implementations on Foreign Types

Convert None into a null pointer.

Implementors