使用带有 Python 的 ctypes 的意外行为

Unexpected behavior using ctypes with Python

我已经隔离了一些我在 Python 中使用 ctypes 时看到的奇怪行为。显然我误解了一些概念,我无法确定它。

代码:

from ctypes import *

class dnpControlPacket(Structure):
    _pack_ = 1
    _fields_ = [
            ("dir", c_bool),
            ("prm", c_bool),
            ("fcb", c_bool),
            ("fcv", c_bool),
            ("fc0", c_bool),
            ("fc1", c_bool),
            ("fc2", c_bool),
            ("fc3", c_bool)
            ]

class ctrlUnion(Union):
    _pack_ = 1
    _fields_ = [
            ("data", dnpControlPacket),
            ("bits", c_bool * 8),
            ("bytes", c_uint8 * 1)
            ]

ctrl = dnpControlPacket(1,1,0,0,0,0,0,0)
cu = ctrlUnion(ctrl)
print("bit format: %s" % [x for x in cu.bits])
print("byte format: %d" % cu.bytes[0])

我的目标是使用 Union (cu) 以字节形式读取数据。奇怪的是,字节的值是 1 而各个位是 '11000000'。我希望字节的值是 192?即

int('11000000', 2)

谁能帮我看看哪里出了问题?

ctypes c_bool 由 C _Bool 数据类型实现(a.k.a bool 自 C99 以来)。它占用最小的可寻址 space,通常为 1 个字节,与 unsigned char 非常相似。不同之处在于,任何非零赋值都会被编译器转换为 1。如果你想要命名位,你在 ctypes 中最接近的是 Bit field