Skip to main content

pyo3_ffi/
methodobject.rs

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