From 5cf29cea9368d10ffe4c2dc1c00390c40003c462 Mon Sep 17 00:00:00 2001 From: serge-sans-paille Date: Sun, 5 Jun 2022 11:06:07 +0200 Subject: [PATCH] Add support for casting nullptr in _Py_CAST_impl Fix #93442 --- Include/pyport.h | 17 +++++++++++++++++ Lib/test/_testcppext.cpp | 8 ++++++++ 2 files changed, 25 insertions(+) diff --git a/Include/pyport.h b/Include/pyport.h index 6ea2bba232b3dd..fedcdb401c0513 100644 --- a/Include/pyport.h +++ b/Include/pyport.h @@ -27,6 +27,22 @@ # define _Py_STATIC_CAST(type, expr) static_cast(expr) extern "C++" { namespace { + + // Overloads to cope with NULL and nullptr + template + inline type _Py_CAST_impl(long int ptr) { + return reinterpret_cast(ptr); + } + template + inline type _Py_CAST_impl(int ptr) { + return reinterpret_cast(ptr); + } + template + inline type _Py_CAST_impl(std::nullptr_t) { + return static_cast(nullptr); + } + + // Overloads to cope with regular pointers template inline type _Py_CAST_impl(expr_type *expr) { return reinterpret_cast(expr); @@ -37,6 +53,7 @@ extern "C++" { return reinterpret_cast(const_cast(expr)); } + // Overloads to cope with object that defines a conversion to `type` template inline type _Py_CAST_impl(expr_type &expr) { return static_cast(expr); diff --git a/Lib/test/_testcppext.cpp b/Lib/test/_testcppext.cpp index eade7ccdaaff7a..f2eee00d04a599 100644 --- a/Lib/test/_testcppext.cpp +++ b/Lib/test/_testcppext.cpp @@ -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; }