Skip to content

Commit 4caf5c2

Browse files
authored
gh-91321: Fix compatibility with C++ older than C++11 (#93784)
Fix the compatibility of the Python C API with C++ older than C++11. _Py_NULL is only defined as nullptr on C++11 and newer.
1 parent 3597c12 commit 4caf5c2

File tree

5 files changed

+76
-36
lines changed

5 files changed

+76
-36
lines changed

Include/pyport.h

+5-2
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,12 @@ extern "C++" {
3636
inline type _Py_CAST_impl(int ptr) {
3737
return reinterpret_cast<type>(ptr);
3838
}
39+
#if __cplusplus >= 201103
3940
template <typename type>
4041
inline type _Py_CAST_impl(std::nullptr_t) {
4142
return static_cast<type>(nullptr);
4243
}
44+
#endif
4345

4446
template <typename type, typename expr_type>
4547
inline type _Py_CAST_impl(expr_type *expr) {
@@ -70,8 +72,9 @@ extern "C++" {
7072
#endif
7173

7274
// Static inline functions should use _Py_NULL rather than using directly NULL
73-
// to prevent C++ compiler warnings. In C++, _Py_NULL uses nullptr.
74-
#ifdef __cplusplus
75+
// to prevent C++ compiler warnings. On C++11 and newer, _Py_NULL is defined as
76+
// nullptr.
77+
#if defined(__cplusplus) && __cplusplus >= 201103
7578
# define _Py_NULL nullptr
7679
#else
7780
# define _Py_NULL NULL

Lib/test/_testcppext.cpp

+30-16
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,12 @@
66

77
#include "Python.h"
88

9+
#if __cplusplus >= 201103
10+
# define NAME _testcpp11ext
11+
#else
12+
# define NAME _testcpp03ext
13+
#endif
14+
915
PyDoc_STRVAR(_testcppext_add_doc,
1016
"add(x, y)\n"
1117
"\n"
@@ -16,7 +22,7 @@ _testcppext_add(PyObject *Py_UNUSED(module), PyObject *args)
1622
{
1723
long i, j;
1824
if (!PyArg_ParseTuple(args, "ll:foo", &i, &j)) {
19-
return nullptr;
25+
return _Py_NULL;
2026
}
2127
long res = i + j;
2228
return PyLong_FromLong(res);
@@ -47,8 +53,8 @@ static PyObject *
4753
test_api_casts(PyObject *Py_UNUSED(module), PyObject *Py_UNUSED(args))
4854
{
4955
PyObject *obj = Py_BuildValue("(ii)", 1, 2);
50-
if (obj == nullptr) {
51-
return nullptr;
56+
if (obj == _Py_NULL) {
57+
return _Py_NULL;
5258
}
5359
Py_ssize_t refcnt = Py_REFCNT(obj);
5460
assert(refcnt >= 1);
@@ -77,9 +83,11 @@ test_api_casts(PyObject *Py_UNUSED(module), PyObject *Py_UNUSED(args))
7783
// gh-93442: Pass 0 as NULL for PyObject*
7884
Py_XINCREF(0);
7985
Py_XDECREF(0);
80-
// ensure that nullptr works too
86+
#if _cplusplus >= 201103
87+
// Test nullptr passed as PyObject*
8188
Py_XINCREF(nullptr);
8289
Py_XDECREF(nullptr);
90+
#endif
8391

8492
Py_DECREF(obj);
8593
Py_RETURN_NONE;
@@ -90,16 +98,16 @@ static PyObject *
9098
test_unicode(PyObject *Py_UNUSED(module), PyObject *Py_UNUSED(args))
9199
{
92100
PyObject *str = PyUnicode_FromString("abc");
93-
if (str == nullptr) {
94-
return nullptr;
101+
if (str == _Py_NULL) {
102+
return _Py_NULL;
95103
}
96104

97105
assert(PyUnicode_Check(str));
98106
assert(PyUnicode_GET_LENGTH(str) == 3);
99107

100108
// gh-92800: test PyUnicode_READ()
101109
const void* data = PyUnicode_DATA(str);
102-
assert(data != nullptr);
110+
assert(data != _Py_NULL);
103111
int kind = PyUnicode_KIND(str);
104112
assert(kind == PyUnicode_1BYTE_KIND);
105113
assert(PyUnicode_READ(kind, data, 0) == 'a');
@@ -118,9 +126,9 @@ test_unicode(PyObject *Py_UNUSED(module), PyObject *Py_UNUSED(args))
118126

119127
static PyMethodDef _testcppext_methods[] = {
120128
{"add", _testcppext_add, METH_VARARGS, _testcppext_add_doc},
121-
{"test_api_casts", test_api_casts, METH_NOARGS, nullptr},
122-
{"test_unicode", test_unicode, METH_NOARGS, nullptr},
123-
{nullptr, nullptr, 0, nullptr} /* sentinel */
129+
{"test_api_casts", test_api_casts, METH_NOARGS, _Py_NULL},
130+
{"test_unicode", test_unicode, METH_NOARGS, _Py_NULL},
131+
{_Py_NULL, _Py_NULL, 0, _Py_NULL} /* sentinel */
124132
};
125133

126134

@@ -135,26 +143,32 @@ _testcppext_exec(PyObject *module)
135143

136144
static PyModuleDef_Slot _testcppext_slots[] = {
137145
{Py_mod_exec, reinterpret_cast<void*>(_testcppext_exec)},
138-
{0, nullptr}
146+
{0, _Py_NULL}
139147
};
140148

141149

142150
PyDoc_STRVAR(_testcppext_doc, "C++ test extension.");
143151

152+
#define _STR(NAME) #NAME
153+
#define STR(NAME) _STR(NAME)
154+
144155
static struct PyModuleDef _testcppext_module = {
145156
PyModuleDef_HEAD_INIT, // m_base
146-
"_testcppext", // m_name
157+
STR(NAME), // m_name
147158
_testcppext_doc, // m_doc
148159
0, // m_size
149160
_testcppext_methods, // m_methods
150161
_testcppext_slots, // m_slots
151-
nullptr, // m_traverse
152-
nullptr, // m_clear
153-
nullptr, // m_free
162+
_Py_NULL, // m_traverse
163+
_Py_NULL, // m_clear
164+
_Py_NULL, // m_free
154165
};
155166

167+
#define _FUNC_NAME(NAME) PyInit_ ## NAME
168+
#define FUNC_NAME(NAME) _FUNC_NAME(NAME)
169+
156170
PyMODINIT_FUNC
157-
PyInit__testcppext(void)
171+
FUNC_NAME(NAME)(void)
158172
{
159173
return PyModuleDef_Init(&_testcppext_module);
160174
}

Lib/test/setup_testcppext.py

+14-5
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,6 @@
1313
if not MS_WINDOWS:
1414
# C++ compiler flags for GCC and clang
1515
CPPFLAGS = [
16-
# Python currently targets C++11
17-
'-std=c++11',
1816
# gh-91321: The purpose of _testcppext extension is to check that building
1917
# a C++ extension using the Python C API does not emit C++ compiler
2018
# warnings
@@ -30,12 +28,23 @@
3028

3129

3230
def main():
31+
cppflags = list(CPPFLAGS)
32+
if '-std=c++03' in sys.argv:
33+
sys.argv.remove('-std=c++03')
34+
std = 'c++03'
35+
name = '_testcpp03ext'
36+
else:
37+
# Python currently targets C++11
38+
std = 'c++11'
39+
name = '_testcpp11ext'
40+
41+
cppflags = [*CPPFLAGS, f'-std={std}']
3342
cpp_ext = Extension(
34-
'_testcppext',
43+
name,
3544
sources=[SOURCE],
3645
language='c++',
37-
extra_compile_args=CPPFLAGS)
38-
setup(name="_testcppext", ext_modules=[cpp_ext])
46+
extra_compile_args=cppflags)
47+
setup(name=name, ext_modules=[cpp_ext])
3948

4049

4150
if __name__ == "__main__":

Lib/test/test_cppext.py

+25-13
Original file line numberDiff line numberDiff line change
@@ -16,22 +16,29 @@
1616

1717
@support.requires_subprocess()
1818
class TestCPPExt(unittest.TestCase):
19+
def test_build_cpp11(self):
20+
self.check_build(False)
21+
22+
def test_build_cpp03(self):
23+
self.check_build(True)
24+
1925
# With MSVC, the linker fails with: cannot open file 'python311.lib'
2026
# https://github.com/python/cpython/pull/32175#issuecomment-1111175897
2127
@unittest.skipIf(MS_WINDOWS, 'test fails on Windows')
2228
# the test uses venv+pip: skip if it's not available
2329
@support.requires_venv_with_pip()
24-
def test_build(self):
30+
def check_build(self, std_cpp03):
2531
# Build in a temporary directory
2632
with os_helper.temp_cwd():
27-
self._test_build()
33+
self._check_build(std_cpp03)
2834

29-
def _test_build(self):
35+
def _check_build(self, std_cpp03):
3036
venv_dir = 'env'
37+
verbose = support.verbose
3138

3239
# Create virtual environment to get setuptools
3340
cmd = [sys.executable, '-X', 'dev', '-m', 'venv', venv_dir]
34-
if support.verbose:
41+
if verbose:
3542
print()
3643
print('Run:', ' '.join(cmd))
3744
subprocess.run(cmd, check=True)
@@ -46,16 +53,21 @@ def _test_build(self):
4653
python = os.path.join(venv_dir, 'bin', python_exe)
4754

4855
# Build the C++ extension
49-
cmd = [python, '-X', 'dev', SETUP_TESTCPPEXT, 'build_ext', '--verbose']
50-
if support.verbose:
56+
cmd = [python, '-X', 'dev',
57+
SETUP_TESTCPPEXT, 'build_ext', '--verbose']
58+
if std_cpp03:
59+
cmd.append('-std=c++03')
60+
if verbose:
5161
print('Run:', ' '.join(cmd))
52-
proc = subprocess.run(cmd,
53-
stdout=subprocess.PIPE,
54-
stderr=subprocess.STDOUT,
55-
text=True)
56-
if proc.returncode:
57-
print(proc.stdout, end='')
58-
self.fail(f"Build failed with exit code {proc.returncode}")
62+
subprocess.run(cmd, check=True)
63+
else:
64+
proc = subprocess.run(cmd,
65+
stdout=subprocess.PIPE,
66+
stderr=subprocess.STDOUT,
67+
text=True)
68+
if proc.returncode:
69+
print(proc.stdout, end='')
70+
self.fail(f"Build failed with exit code {proc.returncode}")
5971

6072

6173
if __name__ == "__main__":
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix the compatibility of the Python C API with C++ older than C++11. Patch by
2+
Victor Stinner.

0 commit comments

Comments
 (0)