Skip to content

Commit 8ac158a

Browse files
bpo-21983: Fix a crash in ctypes.cast() when passed a ctypes structured data type (GH-3859)
(cherry picked from commit d518d8b) Co-authored-by: Oren Milman <[email protected]>
1 parent fa40fc0 commit 8ac158a

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

Lib/ctypes/test/test_cast.py

Lines changed: 13 additions & 0 deletions
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()
Lines changed: 2 additions & 0 deletions
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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5327,7 +5327,7 @@ cast_check_pointertype(PyObject *arg)
53275327
if (PyCFuncPtrTypeObject_Check(arg))
53285328
return 1;
53295329
dict = PyType_stgdict(arg);
5330-
if (dict) {
5330+
if (dict != NULL && dict->proto != NULL) {
53315331
if (PyUnicode_Check(dict->proto)
53325332
&& (strchr("sPzUZXO", PyUnicode_AsUTF8(dict->proto)[0]))) {
53335333
/* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */

0 commit comments

Comments
 (0)