]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-93442: Make C++ version of _Py_CAST work with 0/NULL. (#93500)
authorNeil Schemenauer <nas-github@arctrix.com>
Sun, 5 Jun 2022 01:49:39 +0000 (18:49 -0700)
committerGitHub <noreply@github.com>
Sun, 5 Jun 2022 01:49:39 +0000 (18:49 -0700)
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
Include/pyport.h
Lib/test/_testcppext.cpp
Misc/NEWS.d/next/C API/2022-06-04-13-15-41.gh-issue-93442.4M4NDb.rst [new file with mode: 0644]

index 6ea2bba232b3dd9566b5985d67b2e5ec6646609a..faaeb8329181196c2b745f0aaa11b438be37c11e 100644 (file)
 //
 // 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);
index eade7ccdaaff7af6cc9ac33fc03ae584d8ef58c5..70f434e6789ad7283b57ce8233322753bf4bf76f 100644 (file)
@@ -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);
+
     Py_DECREF(obj);
     Py_RETURN_NONE;
 }
diff --git a/Misc/NEWS.d/next/C API/2022-06-04-13-15-41.gh-issue-93442.4M4NDb.rst b/Misc/NEWS.d/next/C API/2022-06-04-13-15-41.gh-issue-93442.4M4NDb.rst
new file mode 100644 (file)
index 0000000..f48ed37
--- /dev/null
@@ -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.