Skip to content Skip to sidebar Skip to footer

Access Byte By Byte In Python Ctypes Class(structure)

This is a followup question to my question , that was left unanswered EDIT and organized from my module: class t_data_block(Structure): _fields_ = [('current_readings',c_ulong * PO

Solution 1:

Check out buffer:

from binascii importhexlifyx= t_input_buff()

x.header = 1
x.sys_flags.Alarm1 = 1
x.sys_flags.Alarm2 = 0
x.sys_flags.reserved = 0x15555555
x.data_block[0].current_readings[0] = 2
x.data_block[0].current_readings[1] = 3
x.data_block[0].power_reading = 4
x.data_block[1].current_readings[0] = 5
x.data_block[1].current_readings[1] = 6
x.data_block[1].power_reading = 7

b = buffer(x)
print hexlify(b[:])

Output:

0100000055555555020000000300000004000000050000000600000007000000

You can also use ctypes casting:

p=cast(byref(x),POINTER(c_byte*sizeof(x)))
print p.contents[:]

Output:

[1, 0, 0, 0, 85, 85, 85, 85, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 5, 0, 0, 0, 6, 0, 0, 0, 7, 0, 0, 0]

Note: In Python 3, buffer no longer exists. bytes, and list(bytes(...)) give the equivalent of buffer and the ctypes casting example.

Solution 2:

I don't know what is the actual type of your "buff" variable, but you can try to explicitly convert it to string in the loop head

for curChar in str(buff):

Solution 3:

I found the solution:(i shortened the original structures for easier understanding)

from ctypes import*  

classt_mem_fields(Structure):
    _fields_ = [("header",c_ulong),
                ("log", c_byte *  10)]             

classt_mem(Union):
    _fields_ = [("st_field",t_mem_fields),
                ("byte_index",c_byte * 14)]  

defcalc(buff,len):
    sum = 0print(type(buff))
    for cur_byte in buff.byte_index:
         print"cur_byte = %x" %cur_byte
         sum += cur_byte
    print"sum = %x" %sumreturnsumdefmain():
    mem1 = t_mem()
    mem1.st_field.header = 0x12345678
    mem1.byte_index[4] = 1
    mem1.byte_index[5] = 2
    mem1.byte_index[6] = 3
    mem1.byte_index[7] = 4

   calc(mem1,14)

main()

Post a Comment for "Access Byte By Byte In Python Ctypes Class(structure)"