From e97944a27e836f68f6b42393885999f3bcdce36b Mon Sep 17 00:00:00 2001 From: Victor Stinner Date: Wed, 29 Jul 2015 14:37:17 +0200 Subject: Issue #23319: Fix ctypes.BigEndianStructure, swap correctly bytes. Patch written by Matthieu Gautier. --- Lib/ctypes/test/test_bitfields.py | 28 ++++++++++++++++++++++++++++ Misc/NEWS | 3 +++ Modules/_ctypes/cfield.c | 1 + 3 files changed, 32 insertions(+) diff --git a/Lib/ctypes/test/test_bitfields.py b/Lib/ctypes/test/test_bitfields.py index 991dbe8..a854d2b 100644 --- a/Lib/ctypes/test/test_bitfields.py +++ b/Lib/ctypes/test/test_bitfields.py @@ -259,5 +259,33 @@ class BitFieldTest(unittest.TestCase): x.a = 0xFEDCBA9876543211 self.assertEqual(x.a, 0xFEDCBA9876543211) + @need_symbol('c_uint32') + def test_uint32_swap_little_endian(self): + # Issue #23319 + class Little(LittleEndianStructure): + _fields_ = [("a", c_uint32, 24), + ("b", c_uint32, 4), + ("c", c_uint32, 4)] + b = bytearray(4) + x = Little.from_buffer(b) + x.a = 0xabcdef + x.b = 1 + x.c = 2 + self.assertEqual(b, b'\xef\xcd\xab\x21') + + @need_symbol('c_uint32') + def test_uint32_swap_big_endian(self): + # Issue #23319 + class Big(BigEndianStructure): + _fields_ = [("a", c_uint32, 24), + ("b", c_uint32, 4), + ("c", c_uint32, 4)] + b = bytearray(4) + x = Big.from_buffer(b) + x.a = 0xabcdef + x.b = 1 + x.c = 2 + self.assertEqual(b, b'\xab\xcd\xef\x12') + if __name__ == "__main__": unittest.main() diff --git a/Misc/NEWS b/Misc/NEWS index e861175..65bb837 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -34,6 +34,9 @@ Core and Builtins Library ------- +- Issue #23319: Fix ctypes.BigEndianStructure, swap correctly bytes. Patch + written by Matthieu Gautier. + - Issue #23254: Document how to close the TCPServer listening socket. Patch from Martin Panter. diff --git a/Modules/_ctypes/cfield.c b/Modules/_ctypes/cfield.c index 76c72f8..85b5ad2 100644 --- a/Modules/_ctypes/cfield.c +++ b/Modules/_ctypes/cfield.c @@ -769,6 +769,7 @@ I_set_sw(void *ptr, PyObject *value, Py_ssize_t size) if (get_ulong(value, &val) < 0) return NULL; memcpy(&field, ptr, sizeof(field)); + field = SWAP_INT(field); field = SET(unsigned int, field, (unsigned int)val, size); field = SWAP_INT(field); memcpy(ptr, &field, sizeof(field)); -- cgit v0.12