gpt4 book ai didi

python - 如何比较两个 ctypes 对象是否相等?

转载 作者:太空宇宙 更新时间:2023-11-03 13:43:57 24 4
gpt4 key购买 nike

import ctypes as 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

相等运算符 '==' 在上面的简单情况下给出 False。有什么直接的方法吗?

编辑:

这里有一个稍微改进的版本(基于已接受的答案),它也可以处理嵌套数组:

import ctypes as ct

class CtStruct(ct.Structure):

def __eq__(self, other):
for 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 and a[:] != b[:] or not is_array and a != b:
return False
return True

def __ne__(self, other):
for 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 and a[:] != b[:] or not is_array and a != b:
return True
return 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

最佳答案

创建一个类MyCtStructure,那么它的所有子类都不需要实现__eq__ & __ne__。在您的案例中,定义 eq 不再是一件乏味的工作。

import ctypes as ct
class MyCtStructure(ct.Structure):

def __eq__(self, other):
for fld in self._fields_:
if getattr(self, fld[0]) != getattr(other, fld[0]):
return False
return True

def __ne__(self, other):
for fld in self._fields_:
if getattr(self, fld[0]) != getattr(other, fld[0]):
return True
return 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 对象是否相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24307022/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com