Skip to content

Commit d518d8b

Browse files
orenmnzooba
authored andcommitted
bpo-21983: Fix a crash in ctypes.cast() when passed a ctypes structured data type (GH-3859)
1 parent 8cf4b34 commit d518d8b

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

Lib/ctypes/test/test_cast.py

+13
Original file line numberDiff line numberDiff line change
@@ -82,5 +82,18 @@ def test_wchar_p(self):
8282
self.assertEqual(cast(cast(s, c_void_p), c_wchar_p).value,
8383
"hiho")
8484

85+
def test_bad_type_arg(self):
86+
# The type argument must be a ctypes pointer type.
87+
array_type = c_byte * sizeof(c_int)
88+
array = array_type()
89+
self.assertRaises(TypeError, cast, array, None)
90+
self.assertRaises(TypeError, cast, array, array_type)
91+
class Struct(Structure):
92+
_fields_ = [("a", c_int)]
93+
self.assertRaises(TypeError, cast, array, Struct)
94+
class MyUnion(Union):
95+
_fields_ = [("a", c_int)]
96+
self.assertRaises(TypeError, cast, array, MyUnion)
97+
8598
if __name__ == "__main__":
8699
unittest.main()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix a crash in `ctypes.cast()` in case the type argument is a ctypes
2+
structured data type. Patch by Eryk Sun and Oren Milman.

Modules/_ctypes/_ctypes.c

+1-1
Original file line numberDiff line numberDiff line change
@@ -5319,7 +5319,7 @@ cast_check_pointertype(PyObject *arg)
53195319
if (PyCFuncPtrTypeObject_Check(arg))
53205320
return 1;
53215321
dict = PyType_stgdict(arg);
5322-
if (dict) {
5322+
if (dict != NULL && dict->proto != NULL) {
53235323
if (PyUnicode_Check(dict->proto)
53245324
&& (strchr("sPzUZXO", PyUnicode_AsUTF8(dict->proto)[0]))) {
53255325
/* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */

0 commit comments

Comments
 (0)