简体   繁体   中英

Unexpected behavior using ctypes with Python

I've isolated some strange behavior I'm seeing while using ctypes with Python. Clearly I misunderstand some concept and I'm having trouble pinning it down.

Code:

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])

My goal is to read the data in byte form using the Union (cu). Strangely, the value of the byte is 1 while the individual bits are '11000000' . I'd expect the value of the byte to be 192 ? ie

int('11000000', 2)

Can someone help show me where I'm going wrong with this?

ctypes c_bool is implemented by the C _Bool data type (aka bool since C99). It occupies the smallest addressable space which is typically 1 byte and is quite similar to unsigned char . The difference is that any non-zero assignment is converted to 1 by the compiler. If you want named bits, the closest you get in ctypes is a Bit field

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM