|
14 | 14 | #endif |
15 | 15 |
|
16 | 16 |
|
17 | | -// Macro to use C++ static_cast<> and reinterpret_cast<> in the Python C API |
| 17 | +// Macro to use C++ static_cast<>, reinterpret_cast<> and const_cast<> |
| 18 | +// in the Python C API. |
| 19 | +// |
| 20 | +// In C++, _Py_reinterpret_cast(type, expr) converts a constant expression to a |
| 21 | +// non constant type using const_cast<type>. For example, |
| 22 | +// _Py_reinterpret_cast(PyObject*, op) can convert a "const PyObject*" to |
| 23 | +// "PyObject*". |
| 24 | +// |
| 25 | +// The type argument must not be constant. For example, in C++, |
| 26 | +// _Py_reinterpret_cast(const PyObject*, expr) fails with a compiler error. |
18 | 27 | #ifdef __cplusplus |
19 | 28 | # define _Py_static_cast(type, expr) static_cast<type>(expr) |
20 | | -# define _Py_reinterpret_cast(type, expr) reinterpret_cast<type>(expr) |
| 29 | +# define _Py_reinterpret_cast(type, expr) \ |
| 30 | + const_cast<type>(reinterpret_cast<const type>(expr)) |
21 | 31 | #else |
22 | 32 | # define _Py_static_cast(type, expr) ((type)(expr)) |
23 | 33 | # define _Py_reinterpret_cast(type, expr) ((type)(expr)) |
@@ -307,10 +317,10 @@ extern "C" { |
307 | 317 | */ |
308 | 318 | #ifdef Py_DEBUG |
309 | 319 | # define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) \ |
310 | | - (assert((WIDE)(NARROW)(VALUE) == (VALUE)), (NARROW)(VALUE)) |
| 320 | + (assert(_Py_static_cast(WIDE, _Py_static_cast(NARROW, (VALUE))) == (VALUE)), \ |
| 321 | + _Py_static_cast(NARROW, (VALUE))) |
311 | 322 | #else |
312 | | -# define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) \ |
313 | | - _Py_reinterpret_cast(NARROW, (VALUE)) |
| 323 | +# define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) _Py_static_cast(NARROW, (VALUE)) |
314 | 324 | #endif |
315 | 325 |
|
316 | 326 |
|
|
0 commit comments