Skip to content

Commit 8bcc3fa

Browse files
authored
gh-93442: Make C++ version of _Py_CAST work with 0/NULL. (#93500)
Add C++ overloads for _Py_CAST_impl() to handle 0/NULL. This will allow C++ extensions that pass 0 or NULL to macros using _Py_CAST() to continue to compile. Without this, you get an error like: invalid ‘static_cast’ from type ‘int’ to type ‘_object*’ The modern way to use a NULL value in C++ is to use nullptr. However, we want to not break extensions that do things the old way. Co-authored-by: serge-sans-paille
1 parent 3d647e7 commit 8bcc3fa

File tree

3 files changed

+21
-0
lines changed

3 files changed

+21
-0
lines changed

Include/pyport.h

+14
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,23 @@
2424
//
2525
// The type argument must not be a constant type.
2626
#ifdef __cplusplus
27+
#include <cstddef>
2728
# define _Py_STATIC_CAST(type, expr) static_cast<type>(expr)
2829
extern "C++" {
2930
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+
template <typename type>
40+
inline type _Py_CAST_impl(std::nullptr_t) {
41+
return static_cast<type>(nullptr);
42+
}
43+
3044
template <typename type, typename expr_type>
3145
inline type _Py_CAST_impl(expr_type *expr) {
3246
return reinterpret_cast<type>(expr);

Lib/test/_testcppext.cpp

+4
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,10 @@ test_api_casts(PyObject *Py_UNUSED(module), PyObject *Py_UNUSED(args))
7474
Py_INCREF(strong_ref);
7575
Py_DECREF(strong_ref);
7676

77+
// gh-93442: Pass 0 as NULL for PyObject*
78+
Py_XINCREF(0);
79+
Py_XDECREF(0);
80+
7781
Py_DECREF(obj);
7882
Py_RETURN_NONE;
7983
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Add C++ overloads for _Py_CAST_impl() to handle 0/NULL. This will allow C++
2+
extensions that pass 0 or NULL to macros using _Py_CAST() to continue to
3+
compile.

0 commit comments

Comments
 (0)