Skip to content

Commit 5ec9283

Browse files
skirpichevvstinner
andauthored
gh-156865: Don't raise exceptions for ctypes.c_float_complex overflows (#156919)
Co-authored-by: Victor Stinner <vstinner@python.org>
1 parent a942c8c commit 5ec9283

3 files changed

Lines changed: 26 additions & 4 deletions

File tree

‎Lib/test/test_ctypes/test_numbers.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,26 @@ def test_float_overflow(self):
240240
if (hasattr(t, "__ctype_le__")):
241241
self.assertRaises(OverflowError, t.__ctype_le__, big_int)
242242

243+
# gh-156865: be silent in overflows of C types
244+
self.assertEqual(ctypes.c_float(3e300).value, float('inf'))
245+
self.assertEqual(ctypes.c_float.__ctype_le__(3e300).value, float('inf'))
246+
self.assertEqual(ctypes.c_float.__ctype_be__(3e300).value, float('inf'))
247+
248+
@unittest.skipUnless(hasattr(ctypes, "c_float_complex"),
249+
"requires C11 complex type")
250+
def test_complex_overflow(self):
251+
# gh-156865: be silent in overflows of C types
252+
self.assertEqual(ctypes.c_float_complex(3e300).value, complex('inf'))
253+
self.assertEqual(ctypes.c_float_complex.__ctype_le__(3e300).value,
254+
complex('inf'))
255+
self.assertEqual(ctypes.c_float_complex.__ctype_be__(3e300).value,
256+
complex('inf'))
257+
self.assertEqual(ctypes.c_float_complex(3e300j).value, complex('infj'))
258+
self.assertEqual(ctypes.c_float_complex.__ctype_le__(3e300j).value,
259+
complex('infj'))
260+
self.assertEqual(ctypes.c_float_complex.__ctype_be__(3e300j).value,
261+
complex('infj'))
262+
243263

244264
if __name__ == '__main__':
245265
unittest.main()
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Don't raise exceptions on overflows in :class:`ctypes.c_float_complex`.
2+
Patch by Sergey B Kirpichev.

‎Modules/_ctypes/cfield.c‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -865,14 +865,14 @@ Zf_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
865865
return NULL;
866866
}
867867
#ifdef WORDS_BIGENDIAN
868-
if (PyFloat_Pack4(c.real, ptr, 1)
869-
|| PyFloat_Pack4(c.imag, ptr + sizeof(float), 1))
868+
if (PyFloat_Pack4((float)c.real, ptr, 1)
869+
|| PyFloat_Pack4((float)c.imag, ptr + sizeof(float), 1))
870870
{
871871
return NULL;
872872
}
873873
#else
874-
if (PyFloat_Pack4(c.real, ptr, 0)
875-
|| PyFloat_Pack4(c.imag, ptr + sizeof(float), 0))
874+
if (PyFloat_Pack4((float)c.real, ptr, 0)
875+
|| PyFloat_Pack4((float)c.imag, ptr + sizeof(float), 0))
876876
{
877877
return NULL;
878878
}

0 commit comments

Comments
 (0)