我在C中有一个枚举数据类型。在python-ctypes中,我应该如何声明?我希望这个枚举变量成为结构的一部分,并且通过memmove对该结构赋值。完成赋值后,我想显示每个变量的值,并对于枚举类型,我还想显示枚举字符串。
我在C中有一个枚举数据类型。在python-ctypes中,我应该如何声明?我希望这个枚举变量成为结构的一部分,并且通过memmove对该结构赋值。完成赋值后,我想显示每个变量的值,并对于枚举类型,我还想显示枚举字符串。
Raj Kumar提出的枚举类存在问题,因为它需要运行__init__
来设置变量中的新值,如果值在C端被更改,则无法使用。以下是修复后的版本:
class EnumerationType(type(c_uint)):
def __new__(metacls, name, bases, dict):
if not "_members_" in dict:
_members_ = {}
for key, value in dict.items():
if not key.startswith("_"):
_members_[key] = value
dict["_members_"] = _members_
else:
_members_ = dict["_members_"]
dict["_reverse_map_"] = { v: k for k, v in _members_.items() }
cls = type(c_uint).__new__(metacls, name, bases, dict)
for key,value in cls._members_.items():
globals()[key] = value
return cls
def __repr__(self):
return "<Enumeration %s>" % self.__name__
class CEnumeration(c_uint):
__metaclass__ = EnumerationType
_members_ = {}
def __repr__(self):
value = self.value
return "<%s.%s: %d>" % (
self.__class__.__name__,
self._reverse_map_.get(value, '(unknown)'),
value
)
def __eq__(self, other):
if isinstance(other, (int, long)):
return self.value == other
return type(self) == type(other) and self.value == other.value
现在可以声明一个CEnumeration
:
class EBoolean(CEnumeration):
FALSE = 0
TRUE = 1
并使用它:
class HeaderStruct(Structure):
_fields_ = [("param1", EBoolean),
("param2", c_uint)]
例子:
>>> header = HeaderStruct()
>>> header.param1
<EBoolean.FALSE: 0>
>>> memmove(addressof(header), b'\x01', 1) # write LSB 0x01 in the boolean
>>> header.param1
<EBoolean.TRUE: 1>
>>> header.param1 == EBoolean.TRUE
True
>>> header.param1 == 1 # as a special case compare against ints
True
>>> header.param1.value
1L
enum.EnumMeta
会导致元类冲突。 - Eryk Sunglobals()
与定义CEnumeration
子类(例如EBoolean
)的模块无关,而是与定义EnumerationType
的模块有关... 所有子类中的所有条目定义都将在那里定义。 - Tcllsys._getframe(1).f_globals.update(_members_)
(并记得删除帧), 或使用 inspect 进行更加 pythonic 的方法。 - Tcll安蒂·哈帕拉(Antti Haapala)非常出色地回答了问题!然而,我在使用Python 3.2.2时遇到了一些小问题,我认为值得注意。不是:
class CEnumeration(c_uint):
__metaclass__ = EnumerationType
_members_ = {}
class CEnumeration(c_uint, metaclass = EnumerationType):
_members_ = {}
def __eq__(self, other):
if isinstance(other, (int, long)):
return self.value == other
return type(self) == type(other) and self.value == other.value
Becomes:
def __eq__(self, other):
if isinstance(other, int):
return self.value == other
return type(self) == type(other) and self.value == other.value
from ctypes import *
def TypedEnumerationType(tp):
class EnumerationType(type(tp)): # type: ignore
def __new__(metacls, name, bases, dict):
if not "_members_" in dict:
_members_ = {}
for key, value in dict.items():
if not key.startswith("_"):
_members_[key] = value
dict["_members_"] = _members_
else:
_members_ = dict["_members_"]
dict["_reverse_map_"] = {v: k for k, v in _members_.items()}
cls = type(tp).__new__(metacls, name, bases, dict)
for key, value in cls._members_.items():
globals()[key] = value
return cls
def __repr__(self):
return "<Enumeration %s>" % self.__name__
return EnumerationType
def TypedCEnumeration(tp):
class CEnumeration(tp, metaclass=TypedEnumerationType(tp)):
_members_ = {}
def __repr__(self):
value = self.value
return f"<{self.__class__.__name__}.{self._reverse_map_.get(value, '(unknown)')}: {value}>"
def __eq__(self, other):
if isinstance(other, int):
return self.value == other
return type(self) == type(other) and self.value == other.value
return CEnumeration
class Foo(TypedCEnumeration(c_uint16)):
A = 42
B = 1337
class Bar(TypedCEnumeration(c_uint8)):
A = 5
B = 23
assert isinstance(Foo(Foo.A), c_uint16)
assert isinstance(Bar(Bar.A), c_uint8)
assert type(Foo.A) == int
assert Foo.A == 42
assert str(Foo(Foo.A)) == "<Foo.A: 42>"
assert str(Bar(Bar.B)) == "<Bar.B: 23>"
class FooBar(Structure):
_pack_ = 1
_fields_ = [("foo", Foo), ("bar", Bar)]
foobar = FooBar(Foo.A, Bar.B)
assert sizeof(foobar) == 3
assert foobar.foo.value == 42
assert foobar.bar.value == 23
assert [int(x) for x in bytes(foobar)] == [42, 0, 23]