[Python-checkins] bpo-39593: Add test on ctypes cfield.c s_set() (GH-18424)

Hai Shi webhook-mailer at python.org
Mon Jun 1 12:54:28 EDT 2020


https://github.com/python/cpython/commit/a97011b9b8c8111f42e1e7594081956136d848da
commit: a97011b9b8c8111f42e1e7594081956136d848da
branch: master
author: Hai Shi <shihai1992 at gmail.com>
committer: GitHub <noreply at github.com>
date: 2020-06-01T18:54:18+02:00
summary:

bpo-39593: Add test on ctypes cfield.c s_set() (GH-18424)

files:
M Lib/ctypes/test/test_struct_fields.py
M Modules/_ctypes/cfield.c

diff --git a/Lib/ctypes/test/test_struct_fields.py b/Lib/ctypes/test/test_struct_fields.py
index 8045cc82679cc..ee8415f3e630c 100644
--- a/Lib/ctypes/test/test_struct_fields.py
+++ b/Lib/ctypes/test/test_struct_fields.py
@@ -46,6 +46,14 @@ class Y(X):
         Y._fields_ = []
         self.assertRaises(AttributeError, setattr, X, "_fields_", [])
 
+    def test_5(self):
+        class X(Structure):
+            _fields_ = (("char", c_char * 5),)
+
+        x = X(b'#' * 5)
+        x.char = b'a\0b\0'
+        self.assertEqual(bytes(x), b'a\x00###')
+
     # __set__ and __get__ should raise a TypeError in case their self
     # argument is not a ctype instance.
     def test___set__(self):
diff --git a/Modules/_ctypes/cfield.c b/Modules/_ctypes/cfield.c
index 7f853190a785e..32a2beeb744f7 100644
--- a/Modules/_ctypes/cfield.c
+++ b/Modules/_ctypes/cfield.c
@@ -1263,7 +1263,9 @@ s_set(void *ptr, PyObject *value, Py_ssize_t length)
     }
 
     data = PyBytes_AS_STRING(value);
-    size = strlen(data); /* XXX Why not Py_SIZE(value)? */
+    // bpo-39593: Use strlen() to truncate the string at the first null character.
+    size = strlen(data);
+
     if (size < length) {
         /* This will copy the terminating NUL character
          * if there is space for it.



More information about the Python-checkins mailing list