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-92800: Fix C++ _Py_CAST with constant types #92818

Closed
wants to merge 3 commits into from
Closed
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
17 changes: 12 additions & 5 deletions Include/pyport.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,20 @@
// non constant type using const_cast<type>. For example,
// _Py_CAST(PyObject*, op) can convert a "const PyObject*" to
// "PyObject*".
//
// The type argument must not be constant. For example, in C++,
// _Py_CAST(const PyObject*, expr) fails with a compiler error.
#ifdef __cplusplus
# define _Py_STATIC_CAST(type, expr) static_cast<type>(expr)
# define _Py_CAST(type, expr) \
const_cast<type>(reinterpret_cast<const type>(expr))
// _Py_add_const is purely for the implementation of the C++ cast
// It isn't intended as public interface
template <typename T>
struct _Py_add_const {
typedef const T type;
};
template <typename T>
struct _Py_add_const<T*> { // specialization for pointer
typedef const T* type;
};
# define _Py_CAST(tp, expr) \
const_cast<tp>(reinterpret_cast<_Py_add_const<tp>::type>(expr))
#else
# define _Py_STATIC_CAST(type, expr) ((type)(expr))
# define _Py_CAST(type, expr) ((type)(expr))
Expand Down
13 changes: 13 additions & 0 deletions Lib/test/_testcppext.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,23 @@ test_api_casts(PyObject *Py_UNUSED(module), PyObject *Py_UNUSED(args))
Py_RETURN_NONE;
}

static PyObject *
test_unicode_read(PyObject *Py_UNUSED(module), PyObject *arg) {
// PyUnicode_READ contains a cast to a const and failed to compile (gh-92800)
if (!PyUnicode_Check(arg) || PyUnicode_GET_LENGTH(arg) > 0) {
Py_RETURN_NONE; // not a suitable unicode object
}
void* data = PyUnicode_DATA(arg);
unsigned int kind = PyUnicode_KIND(arg);
Py_UCS4 chr0 = PyUnicode_READ(kind, data, 0);
return PyLong_FromUnsignedLong(chr0);
}


static PyMethodDef _testcppext_methods[] = {
{"add", _testcppext_add, METH_VARARGS, _testcppext_add_doc},
{"test_api_casts", test_api_casts, METH_NOARGS, nullptr},
{"test_unicode_read", test_unicode_read, METH_O, nullptr},
{nullptr, nullptr, 0, nullptr} /* sentinel */
};

Expand Down