在python ctypes类中逐字节访问(Structure) [英] access byte by byte in python ctypes class(Structure)

查看:590
本文介绍了在python ctypes类中逐字节访问(Structure)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是对我的问题,该问题没有得到解决

编辑并组织

This is a followup question to my question , that was left unanswered
EDIT and organized

我的模块中:

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 中的每个字节,从pc_memory导入*

I need to go over each byte in buff and i tried the following:

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)

我得到在执行 for 命令

我也尝试使用时出现错误:TypeError:'t_input_buff'对象不可迭代 str(buff)没有运气

有什么建议吗?

i also tried use str(buff) with no luck
Any suggestions?

推荐答案

我找到了解决方案:(我简化了原始结构以便于理解)

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

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

这篇关于在python ctypes类中逐字节访问(Structure)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆