Skip to content

Commit 5cf29ce

Browse files
Add support for casting nullptr in _Py_CAST_impl
Fix python#93442
1 parent 3d647e7 commit 5cf29ce

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

Include/pyport.h

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,22 @@
2727
# define _Py_STATIC_CAST(type, expr) static_cast<type>(expr)
2828
extern "C++" {
2929
namespace {
30+
31+
// Overloads to cope with NULL and nullptr
32+
template <typename type>
33+
inline type _Py_CAST_impl(long int ptr) {
34+
return reinterpret_cast<type>(ptr);
35+
}
36+
template <typename type>
37+
inline type _Py_CAST_impl(int ptr) {
38+
return reinterpret_cast<type>(ptr);
39+
}
40+
template <typename type>
41+
inline type _Py_CAST_impl(std::nullptr_t) {
42+
return static_cast<type>(nullptr);
43+
}
44+
45+
// Overloads to cope with regular pointers
3046
template <typename type, typename expr_type>
3147
inline type _Py_CAST_impl(expr_type *expr) {
3248
return reinterpret_cast<type>(expr);
@@ -37,6 +53,7 @@ extern "C++" {
3753
return reinterpret_cast<type>(const_cast<expr_type *>(expr));
3854
}
3955

56+
// Overloads to cope with object that defines a conversion to `type`
4057
template <typename type, typename expr_type>
4158
inline type _Py_CAST_impl(expr_type &expr) {
4259
return static_cast<type>(expr);

Lib/test/_testcppext.cpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,14 @@ 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: handle null pointer variants.
78+
Py_INCREF(nullptr);
79+
Py_DECREF(nullptr);
80+
Py_INCREF(NULL);
81+
Py_DECREF(NULL);
82+
Py_INCREF(0);
83+
Py_DECREF(0);
84+
7785
Py_DECREF(obj);
7886
Py_RETURN_NONE;
7987
}

0 commit comments

Comments
 (0)