Skip to content

Commit

Permalink
bpo-21983: Fix a crash in ctypes.cast() when passed a ctypes structur…
Browse files Browse the repository at this point in the history
…ed data type (GH-3859)

(cherry picked from commit d518d8b)

Co-authored-by: Oren Milman <orenmn@gmail.com>
  • Loading branch information
miss-islington and orenmn authored May 9, 2018
1 parent fa40fc0 commit 8ac158a
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
13 changes: 13 additions & 0 deletions Lib/ctypes/test/test_cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,5 +82,18 @@ def test_wchar_p(self):
self.assertEqual(cast(cast(s, c_void_p), c_wchar_p).value,
"hiho")

def test_bad_type_arg(self):
# The type argument must be a ctypes pointer type.
array_type = c_byte * sizeof(c_int)
array = array_type()
self.assertRaises(TypeError, cast, array, None)
self.assertRaises(TypeError, cast, array, array_type)
class Struct(Structure):
_fields_ = [("a", c_int)]
self.assertRaises(TypeError, cast, array, Struct)
class MyUnion(Union):
_fields_ = [("a", c_int)]
self.assertRaises(TypeError, cast, array, MyUnion)

if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix a crash in `ctypes.cast()` in case the type argument is a ctypes
structured data type. Patch by Eryk Sun and Oren Milman.
2 changes: 1 addition & 1 deletion Modules/_ctypes/_ctypes.c
Original file line number Diff line number Diff line change
Expand Up @@ -5327,7 +5327,7 @@ cast_check_pointertype(PyObject *arg)
if (PyCFuncPtrTypeObject_Check(arg))
return 1;
dict = PyType_stgdict(arg);
if (dict) {
if (dict != NULL && dict->proto != NULL) {
if (PyUnicode_Check(dict->proto)
&& (strchr("sPzUZXO", PyUnicode_AsUTF8(dict->proto)[0]))) {
/* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */
Expand Down

0 comments on commit 8ac158a

Please sign in to comment.