Sunday, 15 February 2015

python - How to compare two ctypes objects for equality? -



python - How to compare two ctypes objects for equality? -

import ctypes ct class point(ct.structure): _fields_ = [ ('x', ct.c_int), ('y', ct.c_int), ] p1 = point(10, 10) p2 = point(10, 10) print p1 == p2 # => false

the equality operator '==' gives false in trivial case above. there straightforward approach?

edit:

here's improved version (based on accepted answer), can deal nested arrays:

import ctypes ct class ctstruct(ct.structure): def __eq__(self, other): field in self._fields_: attr_name = field[0] a, b = getattr(self, attr_name), getattr(other, attr_name) is_array = isinstance(a, ct.array) if is_array , a[:] != b[:] or not is_array , != b: homecoming false homecoming true def __ne__(self, other): field in self._fields_: attr_name = field[0] a, b = getattr(self, attr_name), getattr(other, attr_name) is_array = isinstance(a, ct.array) if is_array , a[:] != b[:] or not is_array , != b: homecoming true homecoming false class point(ctstruct): _fields_ = [ ('x', ct.c_int), ('y', ct.c_int), ('arr', ct.c_int * 2), ] p1 = point(10, 20, (30, 40)) p2 = point(10, 20, (30, 40)) print p1 == p2 # true

create class myctstructure, subclass not need implement __eq__ & __ne__. defining eq not bit tedious job in case anymore.

import ctypes ct class myctstructure(ct.structure): def __eq__(self, other): fld in self._fields_: if getattr(self, fld[0]) != getattr(other, fld[0]): homecoming false homecoming true def __ne__(self, other): fld in self._fields_: if getattr(self, fld[0]) != getattr(other, fld[0]): homecoming true homecoming false class point(myctstructure): _fields_ = [ ('x', ct.c_int), ('y', ct.c_int), ] p1 = point(10, 11) p2 = point(10, 11) print p1 == p2

python ctypes

No comments:

Post a Comment