Skip to content
52 changes: 29 additions & 23 deletions crates/capi/src/methodobject.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use crate::util::{CStrExt, FfiPtrExt};
use core::ffi::{c_char, c_int};
use core::fmt::Debug;
use rustpython_vm::function::{FuncArgs, HeapMethodDef, ItemDoc, PosArgs, PyMethodFlags};
use rustpython_vm::types::c_slots::{kwargs_ptr, split_args};
use rustpython_vm::{AsObject, PyObjectRef, PyRef, PyResult, VirtualMachine};

define_py_check!(fn PyCFunction_Check, types.builtin_function_or_method_type);
Expand Down Expand Up @@ -128,27 +129,36 @@ impl PyMethodDef {
}
}

pub type PyCFunction =
unsafe extern "C" fn(slf: *mut PyObject, args: *mut PyObject) -> *mut PyObject;

pub type PyCFunctionWithKeywords = unsafe extern "C" fn(
slf: *mut PyObject,
args: *mut PyObject,
kwargs: *mut PyObject,
) -> *mut PyObject;

pub type PyCFunctionFast = unsafe extern "C" fn(
slf: *mut PyObject,
args: *const *mut PyObject,
nargs: isize,
) -> *mut PyObject;

pub type PyCFunctionFastWithKeywords = unsafe extern "C" fn(
slf: *mut PyObject,
args: *const *mut PyObject,
nargs: isize,
kwnames: *mut PyObject,
) -> *mut PyObject;

#[repr(C)]
#[derive(Copy, Clone)]
#[allow(non_snake_case)]
pub union PyMethodPointer {
pub PyCFunction: unsafe extern "C" fn(slf: *mut PyObject, args: *mut PyObject) -> *mut PyObject,
pub PyCFunctionWithKeywords: unsafe extern "C" fn(
slf: *mut PyObject,
args: *mut PyObject,
kwargs: *mut PyObject,
) -> *mut PyObject,
pub PyCFunctionFast: unsafe extern "C" fn(
slf: *mut PyObject,
args: *const *mut PyObject,
nargs: isize,
) -> *mut PyObject,
pub PyCFunctionFastWithKeywords: unsafe extern "C" fn(
slf: *mut PyObject,
args: *const *mut PyObject,
nargs: isize,
kwnames: *mut PyObject,
) -> *mut PyObject,
pub PyCFunction: PyCFunction,
pub PyCFunctionWithKeywords: PyCFunctionWithKeywords,
pub PyCFunctionFast: PyCFunctionFast,
pub PyCFunctionFastWithKeywords: PyCFunctionFastWithKeywords,
}

impl Debug for PyMethodPointer {
Expand Down Expand Up @@ -197,16 +207,12 @@ unsafe fn call_function_with_keywords(
.as_ref()
.map(|obj| obj.as_object().as_raw().cast_mut())
.unwrap_or_default();
let arg_tuple = vm.ctx.new_tuple(args.args);
let kwargs = vm.ctx.new_dict();
for (k, v) in args.kwargs {
kwargs.set_item(&*k, v, vm)?;
}
let (arg_tuple, kwargs) = split_args(vm, args)?;
unsafe {
f(
slf_ptr,
arg_tuple.as_object().as_raw().cast_mut(),
kwargs.as_object().as_raw().cast_mut(),
kwargs_ptr(kwargs.as_ref()),
)
.assume_owned_or_err(vm)
}
Expand Down
Loading
Loading