use crate::ffi_ptr_ext::FfiPtrExt;
use crate::impl_::pyfunction::create_py_c_function;
use crate::py_result_ext::PyResultExt;
use crate::types::capsule::PyCapsuleMethods;
use crate::{
ffi,
impl_::pymethods::{self, PyMethodDef},
types::{PyCapsule, PyDict, PyModule, PyTuple},
};
use crate::{Bound, PyAny, PyResult, Python};
use std::cell::UnsafeCell;
use std::ffi::CStr;
use std::ptr::NonNull;
#[repr(transparent)]
pub struct PyCFunction(PyAny);
pyobject_native_type_core!(PyCFunction, pyobject_native_static_type_object!(ffi::PyCFunction_Type), "builtins", "builtin_function_or_method", #checkfunction=ffi::PyCFunction_Check);
impl PyCFunction {
pub fn new_with_keywords<'py>(
py: Python<'py>,
fun: ffi::PyCFunctionWithKeywords,
name: &'static CStr,
doc: &'static CStr,
module: Option<&Bound<'py, PyModule>>,
) -> PyResult<Bound<'py, Self>> {
let def = PyMethodDef::cfunction_with_keywords(name, fun, doc).into_raw();
let def = Box::leak(Box::new(def));
unsafe { create_py_c_function(py, def, module) }
}
pub fn new<'py>(
py: Python<'py>,
fun: ffi::PyCFunction,
name: &'static CStr,
doc: &'static CStr,
module: Option<&Bound<'py, PyModule>>,
) -> PyResult<Bound<'py, Self>> {
let def = PyMethodDef::noargs(name, fun, doc).into_raw();
let def = Box::leak(Box::new(def));
unsafe { create_py_c_function(py, def, module) }
}
pub fn new_closure<'py, F, R>(
py: Python<'py>,
name: Option<&'static CStr>,
doc: Option<&'static CStr>,
closure: F,
) -> PyResult<Bound<'py, Self>>
where
F: Fn(&Bound<'_, PyTuple>, Option<&Bound<'_, PyDict>>) -> R + Send + 'static,
for<'p> R: crate::impl_::callback::IntoPyCallbackOutput<'p, *mut ffi::PyObject>,
{
let name = name.unwrap_or(c"pyo3-closure");
let doc = doc.unwrap_or(c"");
let method_def =
pymethods::PyMethodDef::cfunction_with_keywords(name, run_closure::<F, R>, doc);
let def = method_def.into_raw();
let capsule = PyCapsule::new(
py,
ClosureDestructor::<F> {
closure,
def: UnsafeCell::new(def),
},
Some(CLOSURE_CAPSULE_NAME.to_owned()),
)?;
let data: NonNull<ClosureDestructor<F>> =
capsule.pointer_checked(Some(CLOSURE_CAPSULE_NAME))?.cast();
let method_def = unsafe { data.as_ref().def.get() };
unsafe {
ffi::PyCFunction_NewEx(method_def, capsule.as_ptr(), std::ptr::null_mut())
.assume_owned_or_err(py)
.cast_into_unchecked()
}
}
}
static CLOSURE_CAPSULE_NAME: &CStr = c"pyo3-closure";
unsafe extern "C" fn run_closure<F, R>(
capsule_ptr: *mut ffi::PyObject,
args: *mut ffi::PyObject,
kwargs: *mut ffi::PyObject,
) -> *mut ffi::PyObject
where
F: Fn(&Bound<'_, PyTuple>, Option<&Bound<'_, PyDict>>) -> R + Send + 'static,
for<'py> R: crate::impl_::callback::IntoPyCallbackOutput<'py, *mut ffi::PyObject>,
{
unsafe {
crate::impl_::trampoline::cfunction_with_keywords::inner(
capsule_ptr,
args,
kwargs,
|py, capsule_ptr, args, kwargs| {
let boxed_fn: &ClosureDestructor<F> =
&*(ffi::PyCapsule_GetPointer(capsule_ptr, CLOSURE_CAPSULE_NAME.as_ptr())
as *mut ClosureDestructor<F>);
let args = Bound::ref_from_ptr(py, &args).cast_unchecked::<PyTuple>();
let kwargs = Bound::ref_from_ptr_or_opt(py, &kwargs)
.as_ref()
.map(|b| b.cast_unchecked::<PyDict>());
let result = (boxed_fn.closure)(args, kwargs);
crate::impl_::callback::convert(py, result)
},
)
}
}
struct ClosureDestructor<F> {
closure: F,
def: UnsafeCell<ffi::PyMethodDef>,
}
unsafe impl<F: Send> Send for ClosureDestructor<F> {}
#[repr(transparent)]
#[cfg(not(Py_LIMITED_API))]
pub struct PyFunction(PyAny);
#[cfg(not(Py_LIMITED_API))]
pyobject_native_type_core!(PyFunction, pyobject_native_static_type_object!(ffi::PyFunction_Type), "builtins", "function", #checkfunction=ffi::PyFunction_Check);