[issue47164] [C API] Add private "CAST" macros to clean up casts in C code
STINNER Victor
report at bugs.python.org
Wed Mar 30 08:28:10 EDT 2022
New submission from STINNER Victor <vstinner at python.org>:
Last years, I started to add "CAST" macros like:
#define _PyObject_CAST(op) ((PyObject*)(op))
#define _PyType_CAST(op) (assert(PyType_Check(op)), (PyTypeObject*)(op))
Example of usage:
#define PyObject_TypeCheck(ob, type) PyObject_TypeCheck(_PyObject_CAST(ob), type)
These macros avoids parenthesis. Example without CAST macro:
#define PyCFunction_GET_FLAGS(func) \
(((PyCFunctionObject *)func) -> m_ml -> ml_flags)
Currently, inline cast requires adding parenthesis:
((PyCFunctionObject *)func)
IMO it's more readable with a CAST macro:
#define _PyCFunction_CAST(func) ((PyCFunctionObject *)func)
#define PyCFunction_GET_FLAGS(func) \
(_PyCFunction_CAST(func)->m_ml->ml_flags)
I propose to add more CAST macros.
By the way, the current Python C API is not fully compatible with C++. "(type)expr" C syntax is seen as "old-style cast" in C++ which recommends static_cast<type>(expr), reinterpret_cast<type>(expr), or another kind of cast. But I prefer to discuss C++ in a separated issue ;-) IMO without considering C++, adding CAST macros is worth it for readability.
I am preparing pull requests for add CAST macros and use existing CAST macros.
----------
components: C API
messages: 416350
nosy: vstinner
priority: normal
severity: normal
status: open
title: [C API] Add private "CAST" macros to clean up casts in C code
versions: Python 3.11
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue47164>
_______________________________________
More information about the Python-bugs-list
mailing list