c-types Structure and equality with bytes/bytearray
Michael Hull
mikehulluk at gmail.com
Mon Apr 26 08:40:13 EDT 2021
Hello everyone,
I've been working with ctypes recently, and I've come across what seems to
be some slightly confusing behaviour, when comparing ctype's Structure
against `bytes` and `bytearray` objects
import ctypes
class Int(ctypes.Structure):
_fields_ = [("first_16", ctypes.c_int8),
("second_16", ctypes.c_int8)]
def serialise(self):
return ctypes.string_at(ctypes.addressof(self),
ctypes.sizeof(self))
i_obj= Int(first_16= 65, second_16=66)
print(i_obj.first_16, i_obj.second_16)
i_bytes = i_obj.serialise()
print(list(i_bytes))
assert type(i_bytes) == bytes
i_bytearray = bytearray(i_bytes)
print("obj == bytes =>", i_obj==i_bytes)
print("bytes == obj =>", i_bytes==i_obj)
print("obj == bytearray =>", i_obj==i_bytearray)
print("bytearray == obj =>", i_bytearray==i_obj)
When I run this (Python 3.6, and Python2.7) , the final 4 print statements
give the following:
"""
obj == bytes => False
bytes == obj => False
obj == bytearray => True
bytearray == obj => True
"""
Is this a bit strange -- my understanding was that `bytes` and `bytearray`
would normally be expected to work quite interchangeably with each other?
It also means that:
bytearray == obj => True
bytes == bytearray => True
bytes == obj => False
If anyone has any experience in this area, and can let me know if I'm
overlooking something silly, and guidance would be gratefully appreciated.
Alternatively, I am happy to open up a bug-report if this looks like
unexpected behaviour?
Best wishes,
Mike
More information about the Python-list
mailing list