1
votes

With python struct pack('<B',1) value is packed correctly <01> to one byte but with ctypes I'm not able to get similar result.

Is it possible to get the same result with ctypes?

c_byte seems to be 4 bytes <01000000>.

Sample code added.

class TEST(Structure):
    _fields_ = [("int", c_int),("byte", c_byte)]

test = TEST(2,1)
print test.int
print test.byte

#bytes
print hexlify(buffer(test)[:])

Now print are

2
1
0200000001000000

Bytes should be 0200000001. Is it because of buffer call or should i declare byte alligment somehow?

1
Where do you get that output from? ctypes.sizeof(ctypes.c_byte(1)) returns 1 for me. - Martijn Pieters

1 Answers

2
votes

This is likely to be because of the alignment/padding, use the _pack_ setting:

class TEST(Structure):
    _pack_ = 1
    _fields_ = [("int", c_int),("byte", c_byte)]

test = TEST(2,1)    
print hexlify(test)

Will print 0200000001