summaryrefslogtreecommitdiffstats
path: root/Lib/test/_testcppext.cpp
diff options
context:
space:
mode:
authorVictor Stinner <vstinner@python.org>2022-05-02 15:07:00 (GMT)
committerGitHub <noreply@github.com>2022-05-02 15:07:00 (GMT)
commit031397063e9c22711abfbf90f2617c8785cfc42c (patch)
tree08f64eeab6cbe6cebb51f44ddeb0f329c16ca9d3 /Lib/test/_testcppext.cpp
parentb11243e85e020ed2f524bdd83c339faf11ef03d4 (diff)
downloadcpython-031397063e9c22711abfbf90f2617c8785cfc42c.zip
cpython-031397063e9c22711abfbf90f2617c8785cfc42c.tar.gz
cpython-031397063e9c22711abfbf90f2617c8785cfc42c.tar.bz2
gh-92135: Fix _Py_reinterpret_cast() for const (#92138)
Fix C++ compiler warnings on cast macros, like _PyObject_CAST(), when casting a constant expression to a non constant type: use const_cast<> in C++. * In C++, Py_SAFE_DOWNCAST() now uses static_cast<> rather than reinterpret_cast<>. * Add tests to the _testcppext C++ extension. * test_cppext no longer captures stdout in verbose mode.
Diffstat (limited to 'Lib/test/_testcppext.cpp')
-rw-r--r--Lib/test/_testcppext.cpp31
1 files changed, 31 insertions, 0 deletions
diff --git a/Lib/test/_testcppext.cpp b/Lib/test/_testcppext.cpp
index 14cd1dd..257843b 100644
--- a/Lib/test/_testcppext.cpp
+++ b/Lib/test/_testcppext.cpp
@@ -1,6 +1,9 @@
// gh-91321: Very basic C++ test extension to check that the Python C API is
// compatible with C++ and does not emit C++ compiler warnings.
+// Always enable assertions
+#undef NDEBUG
+
#include "Python.h"
PyDoc_STRVAR(_testcppext_add_doc,
@@ -20,8 +23,36 @@ _testcppext_add(PyObject *Py_UNUSED(module), PyObject *args)
}
+static PyObject *
+test_api_casts(PyObject *Py_UNUSED(module), PyObject *Py_UNUSED(args))
+{
+ PyObject *obj = Py_BuildValue("(ii)", 1, 2);
+ if (obj == nullptr) {
+ return nullptr;
+ }
+
+ // gh-92138: For backward compatibility, functions of Python C API accepts
+ // "const PyObject*". Check that using it does not emit C++ compiler
+ // warnings.
+ const PyObject *const_obj = obj;
+ Py_INCREF(const_obj);
+ Py_DECREF(const_obj);
+ PyTypeObject *type = Py_TYPE(const_obj);
+ assert(Py_REFCNT(const_obj) >= 1);
+
+ assert(type == &PyTuple_Type);
+ assert(PyTuple_GET_SIZE(const_obj) == 2);
+ PyObject *one = PyTuple_GET_ITEM(const_obj, 0);
+ assert(PyLong_AsLong(one) == 1);
+
+ Py_DECREF(obj);
+ Py_RETURN_NONE;
+}
+
+
static PyMethodDef _testcppext_methods[] = {
{"add", _testcppext_add, METH_VARARGS, _testcppext_add_doc},
+ {"test_api_casts", test_api_casts, METH_NOARGS, NULL},
{nullptr, nullptr, 0, nullptr} /* sentinel */
};