Skip to content

Commit 7fc39a2

Browse files
authored
bpo-47164: Add _PyCFunctionObject_CAST() macr (GH-32190)
Add _PyCFunctionObject_CAST() and _PyCMethodObject_CAST() macros to make macros casting their argument easier to read, but also to check the type of their input in debug mode: assert(PyCFunction_Check(func) and assert(PyCMethod_Check(func). Reformat also PyCFunction_XXX() macros for readability.
1 parent f0bc694 commit 7fc39a2

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

Include/cpython/methodobject.h

+11-6
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,23 @@ PyAPI_DATA(PyTypeObject) PyCMethod_Type;
77
#define PyCMethod_CheckExact(op) Py_IS_TYPE(op, &PyCMethod_Type)
88
#define PyCMethod_Check(op) PyObject_TypeCheck(op, &PyCMethod_Type)
99

10+
#define _PyCFunctionObject_CAST(func) \
11+
(assert(PyCFunction_Check(func)), (PyCFunctionObject *)(func))
12+
#define _PyCMethodObject_CAST(func) \
13+
(assert(PyCMethod_Check(func)), (PyCMethodObject *)(func))
14+
1015
/* Macros for direct access to these values. Type checks are *not*
1116
done, so use with care. */
1217
#define PyCFunction_GET_FUNCTION(func) \
13-
(((PyCFunctionObject *)func) -> m_ml -> ml_meth)
18+
(_PyCFunctionObject_CAST(func)->m_ml->ml_meth)
1419
#define PyCFunction_GET_SELF(func) \
15-
(((PyCFunctionObject *)func) -> m_ml -> ml_flags & METH_STATIC ? \
16-
NULL : ((PyCFunctionObject *)func) -> m_self)
20+
(_PyCFunctionObject_CAST(func)->m_ml->ml_flags & METH_STATIC ? \
21+
NULL : _PyCFunctionObject_CAST(func)->m_self)
1722
#define PyCFunction_GET_FLAGS(func) \
18-
(((PyCFunctionObject *)func) -> m_ml -> ml_flags)
23+
(_PyCFunctionObject_CAST(func)->m_ml->ml_flags)
1924
#define PyCFunction_GET_CLASS(func) \
20-
(((PyCFunctionObject *)func) -> m_ml -> ml_flags & METH_METHOD ? \
21-
((PyCMethodObject *)func) -> mm_class : NULL)
25+
(_PyCFunctionObject_CAST(func)->m_ml->ml_flags & METH_METHOD ? \
26+
_PyCMethodObject_CAST(func)->mm_class : NULL)
2227

2328
typedef struct {
2429
PyObject_HEAD

0 commit comments

Comments
 (0)