2011-12-04 22 views
0

這是一個後續問題要my question,這是沒有答案
修改,然後從我的模塊組織訪問字節

class t_data_block(Structure): 
_fields_ = [("current_readings",c_ulong * PORTS_NUM), 
      ("power_reading",c_ulong)] 

class t_sys_flags(Structure): 
"System flags" 
_fields_ = [("Alarm1",c_ulong,1), 
      ("Alarm2",c_ulong,1), 
      ("reserved",c_ulong,30)] 

class t_input_buff(Structure): 
"Input buffer from the board" 
    _fields_ = [("header",c_ulong), 
       ("sys_flags", t_sys_flags),# t_sys_flags is another structure 
       ("data_block", t_data_block * CHIP_NUM)] # t_data_block is another structure 

我需要遍歷buff中的每個字節,我試過以下內容:

from pc_memory import* 
def calc_formula(buff,len): 
    sum = 0 
    for curChar in buff: 
     numericByteValue = ord(curChar) 
     sum += numericByteValue 
    return sum 

def main: 
    input_buff = t_input_buff() 

    calc_formula(input_buff,len) 

,我也得到了時命令

我也嘗試使用str(buff)沒有運氣
任何建議執行「錯誤:‘t_input_buff’對象不是可迭代:類型錯誤」?

+0

請,也給介紹「data_block」結構,所以我可以幫助 –

+0

我更新我的問題與data_block和sys_flags結構定義 –

回答

0

我找到了解決辦法:(我縮短了原來的結構更容易理解)

from ctypes import* 

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

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

def calc(buff,len): 
    sum = 0 
    print(type(buff)) 
    for cur_byte in buff.byte_index: 
     print "cur_byte = %x" %cur_byte 
     sum += cur_byte 
    print "sum = %x" %sum 
    return sum  

def main(): 
    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() 
0

我不知道什麼是實際類型的「迷」可變的,但你可以嘗試明確地將其轉換爲字符串中的循環頭

for curChar in str(buff):

3

退房buffer

from binascii import hexlify 
x = 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[:]) 

輸出:

0100000055555555020000000300000004000000050000000600000007000000 

你也可以使用ctypes的鑄造:

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

輸出:

[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] 
+0

我檢出了'緩衝區',它似乎工作。不過我更喜歡「聯盟」解決方案(也許是因爲我習慣用C語言編寫)。也許我會使用'buffer'選項通過使用offset參數來切片 –