Skip to content

Commit ca96502

Browse files
committed
gh-156865: don't raise exceptions for overflows in the ctypes module
1 parent 5f7d709 commit ca96502

3 files changed

Lines changed: 21 additions & 4 deletions

File tree

Lib/test/test_ctypes/test_numbers.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,21 @@ 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+
self.assertEqual(ctypes.c_float_complex(3e300).value, complex('inf'))
248+
self.assertEqual(ctypes.c_float_complex.__ctype_le__(3e300).value,
249+
complex('inf'))
250+
self.assertEqual(ctypes.c_float_complex.__ctype_be__(3e300).value,
251+
complex('inf'))
252+
self.assertEqual(ctypes.c_float_complex(3e300j).value, complex('infj'))
253+
self.assertEqual(ctypes.c_float_complex.__ctype_le__(3e300j).value,
254+
complex('infj'))
255+
self.assertEqual(ctypes.c_float_complex.__ctype_be__(3e300j).value,
256+
complex('infj'))
257+
243258

244259
if __name__ == '__main__':
245260
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 floating-point types of the
2+
:mod:`ctypes`. 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)