Skip to content

Commit

Permalink
Add support for casting nullptr in _Py_CAST_impl
Browse files Browse the repository at this point in the history
  • Loading branch information
serge-sans-paille committed Jun 5, 2022
1 parent 3d647e7 commit 5cf29ce
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
17 changes: 17 additions & 0 deletions Include/pyport.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,22 @@
# define _Py_STATIC_CAST(type, expr) static_cast<type>(expr)
extern "C++" {
namespace {

// Overloads to cope with NULL and nullptr
template <typename type>
inline type _Py_CAST_impl(long int ptr) {
return reinterpret_cast<type>(ptr);
}
template <typename type>
inline type _Py_CAST_impl(int ptr) {
return reinterpret_cast<type>(ptr);
}
template <typename type>
inline type _Py_CAST_impl(std::nullptr_t) {
return static_cast<type>(nullptr);
}

// Overloads to cope with regular pointers
template <typename type, typename expr_type>
inline type _Py_CAST_impl(expr_type *expr) {
return reinterpret_cast<type>(expr);
Expand All @@ -37,6 +53,7 @@ extern "C++" {
return reinterpret_cast<type>(const_cast<expr_type *>(expr));
}

// Overloads to cope with object that defines a conversion to `type`
template <typename type, typename expr_type>
inline type _Py_CAST_impl(expr_type &expr) {
return static_cast<type>(expr);
Expand Down
8 changes: 8 additions & 0 deletions Lib/test/_testcppext.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,14 @@ test_api_casts(PyObject *Py_UNUSED(module), PyObject *Py_UNUSED(args))
Py_INCREF(strong_ref);
Py_DECREF(strong_ref);

// gh-93442: handle null pointer variants.
Py_INCREF(nullptr);
Py_DECREF(nullptr);
Py_INCREF(NULL);
Py_DECREF(NULL);
Py_INCREF(0);
Py_DECREF(0);

Py_DECREF(obj);
Py_RETURN_NONE;
}
Expand Down

0 comments on commit 5cf29ce

Please sign in to comment.