How do I convert from pyo3::ffi::PyFrameObject to pyo3::types::PyFrame? #2745
-
I'm pretty new to Rust, so I might be missing something. I'm trying to create a Rust implementation of a Python profiler. So far I have got a very basic profiling callback implemented: use pyo3::ffi;
use pyo3::prelude::*;
extern "C" fn profile(
_obj: *mut ffi::PyObject,
_frame: *mut ffi::PyFrameObject,
what: i32,
_arg: *mut ffi::PyObject,
) -> i32 {
if what == ffi::PyTrace_CALL {
println!("Call");
} else if what == ffi::PyTrace_RETURN {
println!("Return");
}
0
}
#[pyfunction]
fn register_profiler(profiler: PyObject) {
unsafe {
ffi::PyEval_SetProfile(Some(profile), profiler.into_ptr());
}
}
/// A Python module implemented in Rust.
#[pymodule]
fn _kolo(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_function(wrap_pyfunction!(register_profiler, m)?)?;
Ok(())
} I now want to update my profile function to call the extern "C" fn profile(
_obj: *mut ffi::PyObject,
_frame: *mut ffi::PyFrameObject,
what: i32,
_arg: *mut ffi::PyObject,
) -> i32 {
if what == ffi::PyTrace_CALL {
println!("Call");
Python::with_gil(|py| {
let obj = PyObject::from_owned_ptr_or_err(py, _obj);
let arg = PyObject::from_owned_ptr_or_err(py, _arg);
let args = (_frame, "call", arg.expect(""));
obj.expect("").call1(py, args);
})
} else if what == ffi::PyTrace_RETURN {
println!("Return");
}
0
} This fails with the following error:
Clearly I need to also convert use pyo3::types::PyFrame;
extern "C" fn profile(
_obj: *mut ffi::PyObject,
_frame: *mut ffi::PyFrameObject,
what: i32,
_arg: *mut ffi::PyObject,
) -> i32 {
if what == ffi::PyTrace_CALL {
println!("Call");
Python::with_gil(|py| {
let obj = PyObject::from_owned_ptr_or_err(py, _obj);
let frame = PyFrame::from_owned_ptr_or_err(py, _frame);
let arg = PyObject::from_owned_ptr_or_err(py, _arg);
let args = (frame.expect(""), "call", arg.expect(""));
obj.expect("").call1(py, args);
})
} else if what == ffi::PyTrace_RETURN {
println!("Return");
}
0
} But this fails:
Adding
At this point I'm stuck. Is there a straightforward way to convert the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
Beta Was this translation helpful? Give feedback.
PyFrameObject
is aPyObject
, so if you don't need aPyFrame
on the Rust side the easiest here is to just take*mut PyObject
in the callback or to cast the*mut PyFrameObject
usingas *mut PyObject
inside of it.