theoneandonly2
theoneandonly2

Reputation: 831

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? i.e.

int('11000000', 2)

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

Upvotes: 0

Views: 87

Answers (1)

tdelaney
tdelaney

Reputation: 77407

ctypes c_bool is implemented by the C _Bool data type (a.k.a 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

Upvotes: 4

Related Questions