Skip to main content

pyo3_ffi/
methodobject.rs

1use crate::object::{PyObject, PyTypeObject};
2#[cfg(not(RustPython))]
3use crate::PyObject_TypeCheck;
4#[cfg(not(RustPython))]
5use crate::Py_IS_TYPE;
6use core::ffi::{c_char, c_int, c_void};
7use core::{mem, ptr};
8
9#[cfg(all(not(Py_LIMITED_API), not(GraalPy)))]
10pub struct PyCFunctionObject {
11    pub ob_base: PyObject,
12    pub m_ml: *mut PyMethodDef,
13    pub m_self: *mut PyObject,
14    pub m_module: *mut PyObject,
15    pub m_weakreflist: *mut PyObject,
16    #[cfg(not(PyPy))]
17    pub vectorcall: Option<crate::vectorcallfunc>,
18}
19
20extern_libpython! {
21    #[cfg(not(RustPython))]
22    #[cfg_attr(PyPy, link_name = "PyPyCFunction_Type")]
23    pub static mut PyCFunction_Type: PyTypeObject;
24
25    #[cfg(RustPython)]
26    pub fn PyCFunction_CheckExact(op: *mut PyObject) -> c_int;
27    #[cfg(RustPython)]
28    pub fn PyCFunction_Check(op: *mut PyObject) -> c_int;
29}
30
31#[cfg(not(RustPython))]
32#[inline]
33pub unsafe fn PyCFunction_CheckExact(op: *mut PyObject) -> c_int {
34    Py_IS_TYPE(op, &raw mut PyCFunction_Type)
35}
36
37#[cfg(not(RustPython))]
38#[inline]
39pub unsafe fn PyCFunction_Check(op: *mut PyObject) -> c_int {
40    PyObject_TypeCheck(op, &raw mut PyCFunction_Type)
41}
42
43pub type PyCFunction =
44    unsafe extern "C" fn(slf: *mut PyObject, args: *mut PyObject) -> *mut PyObject;
45
46#[cfg(any(Py_3_10, not(Py_LIMITED_API)))]
47pub type PyCFunctionFast = unsafe extern "C" fn(
48    slf: *mut PyObject,
49    args: *mut *mut PyObject,
50    nargs: crate::pyport::Py_ssize_t,
51) -> *mut PyObject;
52
53#[cfg(any(Py_3_10, not(Py_LIMITED_API)))]
54#[deprecated(note = "renamed to `PyCFunctionFast`")]
55pub type _PyCFunctionFast = PyCFunctionFast;
56
57pub type PyCFunctionWithKeywords = unsafe extern "C" fn(
58    slf: *mut PyObject,
59    args: *mut PyObject,
60    kwds: *mut PyObject,
61) -> *mut PyObject;
62
63#[cfg(any(Py_3_10, not(Py_LIMITED_API)))]
64pub type PyCFunctionFastWithKeywords = unsafe extern "C" fn(
65    slf: *mut PyObject,
66    args: *const *mut PyObject,
67    nargs: crate::pyport::Py_ssize_t,
68    kwnames: *mut PyObject,
69) -> *mut PyObject;
70
71#[cfg(any(Py_3_10, not(Py_LIMITED_API)))]
72#[deprecated(note = "renamed to `PyCFunctionFastWithKeywords`")]
73pub type _PyCFunctionFastWithKeywords = PyCFunctionFastWithKeywords;
74
75#[cfg(not(Py_LIMITED_API))]
76pub type PyCMethod = unsafe extern "C" fn(
77    slf: *mut PyObject,
78    defining_class: *mut PyTypeObject,
79    args: *const *mut PyObject,
80    nargs: crate::pyport::Py_ssize_t,
81    kwnames: *mut PyObject,
82) -> *mut PyObject;
83
84extern_libpython! {
85    #[cfg_attr(PyPy, link_name = "PyPyCFunction_GetFunction")]
86    pub fn PyCFunction_GetFunction(f: *mut PyObject) -> Option<PyCFunction>;
87    pub fn PyCFunction_GetSelf(f: *mut PyObject) -> *mut PyObject;
88    pub fn PyCFunction_GetFlags(f: *mut PyObject) -> c_int;
89    #[cfg(not(Py_3_13))]
90    #[deprecated(note = "Python 3.9")]
91    pub fn PyCFunction_Call(
92        f: *mut PyObject,
93        args: *mut PyObject,
94        kwds: *mut PyObject,
95    ) -> *mut PyObject;
96}
97
98/// Represents the [PyMethodDef](https://docs.python.org/3/c-api/structures.html#c.PyMethodDef)
99/// structure.
100///
101/// Note that CPython may leave fields uninitialized. You must ensure that
102/// `ml_name` != NULL before dereferencing or reading other fields.
103#[repr(C)]
104#[derive(Copy, Clone, PartialEq, Eq)]
105pub struct PyMethodDef {
106    pub ml_name: *const c_char,
107    pub ml_meth: PyMethodDefPointer,
108    pub ml_flags: c_int,
109    pub ml_doc: *const c_char,
110}
111
112impl PyMethodDef {
113    pub const fn zeroed() -> PyMethodDef {
114        PyMethodDef {
115            ml_name: ptr::null(),
116            ml_meth: PyMethodDefPointer {
117                Void: ptr::null_mut(),
118            },
119            ml_flags: 0,
120            ml_doc: ptr::null(),
121        }
122    }
123}
124
125impl Default for PyMethodDef {
126    fn default() -> PyMethodDef {
127        PyMethodDef {
128            ml_name: ptr::null(),
129            ml_meth: PyMethodDefPointer {
130                Void: ptr::null_mut(),
131            },
132            ml_flags: 0,
133            ml_doc: ptr::null(),
134        }
135    }
136}
137
138/// Function types used to implement Python callables.
139///
140/// This function pointer must be accompanied by the correct [ml_flags](PyMethodDef::ml_flags),
141/// otherwise the behavior is undefined.
142///
143/// See the [Python C API documentation][1] for more information.
144///
145/// [1]: https://docs.python.org/3/c-api/structures.html#implementing-functions-and-methods
146#[repr(C)]
147#[derive(Copy, Clone, Eq)]
148pub union PyMethodDefPointer {
149    /// This variant corresponds with [`METH_VARARGS`] *or* [`METH_NOARGS`] *or* [`METH_O`].
150    pub PyCFunction: PyCFunction,
151
152    /// This variant corresponds with [`METH_VARARGS`] | [`METH_KEYWORDS`].
153    pub PyCFunctionWithKeywords: PyCFunctionWithKeywords,
154
155    /// This variant corresponds with [`METH_FASTCALL`].
156    #[cfg(any(Py_3_10, not(Py_LIMITED_API)))]
157    #[deprecated(note = "renamed to `PyCFunctionFast`")]
158    pub _PyCFunctionFast: PyCFunctionFast,
159
160    /// This variant corresponds with [`METH_FASTCALL`].
161    #[cfg(any(Py_3_10, not(Py_LIMITED_API)))]
162    pub PyCFunctionFast: PyCFunctionFast,
163
164    /// This variant corresponds with [`METH_FASTCALL`] | [`METH_KEYWORDS`].
165    #[cfg(any(Py_3_10, not(Py_LIMITED_API)))]
166    #[deprecated(note = "renamed to `PyCFunctionFastWithKeywords`")]
167    pub _PyCFunctionFastWithKeywords: PyCFunctionFastWithKeywords,
168
169    /// This variant corresponds with [`METH_FASTCALL`] | [`METH_KEYWORDS`].
170    #[cfg(any(Py_3_10, not(Py_LIMITED_API)))]
171    pub PyCFunctionFastWithKeywords: PyCFunctionFastWithKeywords,
172
173    /// This variant corresponds with [`METH_METHOD`] | [`METH_FASTCALL`] | [`METH_KEYWORDS`].
174    #[cfg(not(Py_LIMITED_API))]
175    pub PyCMethod: PyCMethod,
176
177    Void: *mut c_void,
178}
179
180impl PyMethodDefPointer {
181    pub fn as_ptr(&self) -> *mut c_void {
182        // SAFETY: self is pointer sized
183        unsafe { self.Void }
184    }
185
186    pub fn is_null(&self) -> bool {
187        self.as_ptr().is_null()
188    }
189
190    pub const fn zeroed() -> PyMethodDefPointer {
191        PyMethodDefPointer {
192            Void: ptr::null_mut(),
193        }
194    }
195}
196
197impl PartialEq for PyMethodDefPointer {
198    fn eq(&self, other: &Self) -> bool {
199        self.as_ptr() == other.as_ptr()
200    }
201}
202
203impl core::fmt::Pointer for PyMethodDefPointer {
204    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
205        let ptr = self.as_ptr();
206        core::fmt::Pointer::fmt(&ptr, f)
207    }
208}
209
210const _: () =
211    assert!(mem::size_of::<PyMethodDefPointer>() == mem::size_of::<Option<extern "C" fn()>>());
212
213#[inline]
214pub unsafe fn PyCFunction_New(ml: *mut PyMethodDef, slf: *mut PyObject) -> *mut PyObject {
215    PyCFunction_NewEx(ml, slf, core::ptr::null_mut())
216}
217
218#[inline]
219pub unsafe fn PyCFunction_NewEx(
220    ml: *mut PyMethodDef,
221    slf: *mut PyObject,
222    module: *mut PyObject,
223) -> *mut PyObject {
224    PyCMethod_New(ml, slf, module, core::ptr::null_mut())
225}
226
227extern_libpython! {
228    #[cfg_attr(PyPy, link_name = "PyPyCMethod_New")]
229    pub fn PyCMethod_New(
230        ml: *mut PyMethodDef,
231        slf: *mut PyObject,
232        module: *mut PyObject,
233        cls: *mut PyTypeObject,
234    ) -> *mut PyObject;
235}
236
237/* Flag passed to newmethodobject */
238pub const METH_VARARGS: c_int = 0x0001;
239pub const METH_KEYWORDS: c_int = 0x0002;
240/* METH_NOARGS and METH_O must not be combined with the flags above. */
241pub const METH_NOARGS: c_int = 0x0004;
242pub const METH_O: c_int = 0x0008;
243
244/* METH_CLASS and METH_STATIC are a little different; these control
245the construction of methods for a class.  These cannot be used for
246functions in modules. */
247pub const METH_CLASS: c_int = 0x0010;
248pub const METH_STATIC: c_int = 0x0020;
249
250/* METH_COEXIST allows a method to be entered eventhough a slot has
251already filled the entry.  When defined, the flag allows a separate
252method, "__contains__" for example, to coexist with a defined
253slot like sq_contains. */
254
255pub const METH_COEXIST: c_int = 0x0040;
256
257/* METH_FASTCALL indicates the PEP 590 Vectorcall calling format. It may
258be specified alone or with METH_KEYWORDS. */
259#[cfg(any(Py_3_10, not(Py_LIMITED_API)))]
260pub const METH_FASTCALL: c_int = 0x0080;
261
262// skipped METH_STACKLESS
263
264#[cfg(not(Py_LIMITED_API))]
265pub const METH_METHOD: c_int = 0x0200;