Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-93442: Make C++ version of _Py_CAST work with 0/NULL. #93500

Merged
merged 2 commits into from
Jun 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions Include/pyport.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,23 @@
//
// The type argument must not be a constant type.
#ifdef __cplusplus
#include <cstddef>
# define _Py_STATIC_CAST(type, expr) static_cast<type>(expr)
extern "C++" {
namespace {
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);
}

template <typename type, typename expr_type>
inline type _Py_CAST_impl(expr_type *expr) {
return reinterpret_cast<type>(expr);
Expand Down
4 changes: 4 additions & 0 deletions Lib/test/_testcppext.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@ test_api_casts(PyObject *Py_UNUSED(module), PyObject *Py_UNUSED(args))
Py_INCREF(strong_ref);
Py_DECREF(strong_ref);

// gh-93442: Pass 0 as NULL for PyObject*
Py_XINCREF(0);
Py_XDECREF(0);

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit

Suggested change
Py_XINCREF(nullptr);
Py_XDECREF(nullptr);
Py_XINCREF(NULL);
Py_XDECREF(NULL);

Py_DECREF(obj);
Py_RETURN_NONE;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
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.