Skip to content

Commit 3faf13d

Browse files
committed
gh-94731: Use C-style casts for _Py_CAST, even in C++
1 parent f09b8c6 commit 3faf13d

File tree

2 files changed

+3
-53
lines changed

2 files changed

+3
-53
lines changed

Include/pyport.h

+3-51
Original file line numberDiff line numberDiff line change
@@ -14,62 +14,14 @@
1414
#endif
1515

1616

17-
// Macro to use C++ static_cast<>, reinterpret_cast<> and const_cast<>
18-
// in the Python C API.
19-
//
20-
// In C++, _Py_CAST(type, expr) converts a constant expression to a
21-
// non constant type using const_cast<type>. For example,
22-
// _Py_CAST(PyObject*, op) can convert a "const PyObject*" to
23-
// "PyObject*".
24-
//
25-
// The type argument must not be a constant type.
17+
// Macro to use C++ static_cast<> in the Python C API.
2618
#ifdef __cplusplus
27-
#include <cstddef>
2819
# define _Py_STATIC_CAST(type, expr) static_cast<type>(expr)
29-
extern "C++" {
30-
namespace {
31-
template <typename type>
32-
inline type _Py_CAST_impl(long int ptr) {
33-
return reinterpret_cast<type>(ptr);
34-
}
35-
template <typename type>
36-
inline type _Py_CAST_impl(int ptr) {
37-
return reinterpret_cast<type>(ptr);
38-
}
39-
#if __cplusplus >= 201103
40-
template <typename type>
41-
inline type _Py_CAST_impl(std::nullptr_t) {
42-
return static_cast<type>(nullptr);
43-
}
44-
#endif
45-
46-
template <typename type, typename expr_type>
47-
inline type _Py_CAST_impl(expr_type *expr) {
48-
return reinterpret_cast<type>(expr);
49-
}
50-
51-
template <typename type, typename expr_type>
52-
inline type _Py_CAST_impl(expr_type const *expr) {
53-
return reinterpret_cast<type>(const_cast<expr_type *>(expr));
54-
}
55-
56-
template <typename type, typename expr_type>
57-
inline type _Py_CAST_impl(expr_type &expr) {
58-
return static_cast<type>(expr);
59-
}
60-
61-
template <typename type, typename expr_type>
62-
inline type _Py_CAST_impl(expr_type const &expr) {
63-
return static_cast<type>(const_cast<expr_type &>(expr));
64-
}
65-
}
66-
}
67-
# define _Py_CAST(type, expr) _Py_CAST_impl<type>(expr)
68-
6920
#else
7021
# define _Py_STATIC_CAST(type, expr) ((type)(expr))
71-
# define _Py_CAST(type, expr) ((type)(expr))
7222
#endif
23+
// Macro to use the more powerful/dangerous C-style cast even in C++.
24+
#define _Py_CAST(type, expr) ((type)(expr))
7325

7426
// Static inline functions should use _Py_NULL rather than using directly NULL
7527
// to prevent C++ compiler warnings. On C++11 and newer, _Py_NULL is defined as

Lib/test/setup_testcppext.py

-2
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,6 @@
1717
# a C++ extension using the Python C API does not emit C++ compiler
1818
# warnings
1919
'-Werror',
20-
# Warn on old-style cast (C cast) like: (PyObject*)op
21-
'-Wold-style-cast',
2220
]
2321
else:
2422
# Don't pass any compiler flag to MSVC

0 commit comments

Comments
 (0)