加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python的构造 – .sizeof()用于构造,具体取决于其父级

发布时间:2020-12-20 13:18:10 所属栏目:Python 来源:网络整理
导读:这篇文章是关于 Python的 Construct库 代码 这些是我的构造的定义: from construct import *AttributeHandleValuePair = "attribute_handle_value_pair" / Struct( "handle" / Int16ul,"value" / Bytes(this._.length - 2))AttReadByTypeResponse = "read_b
这篇文章是关于 Python的 Construct库

代码

这些是我的构造的定义:

from construct import *

AttributeHandleValuePair = "attribute_handle_value_pair" / Struct(
    "handle" / Int16ul,"value" / Bytes(this._.length - 2)
)

AttReadByTypeResponse = "read_by_type_response" / Struct(
    "length" / Int8ul,# The size in bytes of each handle/value pair
    "attribute_data_list" / AttributeHandleValuePair[2]
)

问题

尝试运行以下命令:

AttReadByTypeResponse.sizeof(dict(length = 4,attribute_data_list = [dict(handle = 1,value = 2),dict(handle = 3,value = 4)])

我收到以下错误:

SizeofError: cannot calculate size,key not found in context
    sizeof -> read_by_type_response -> attribute_data_list -> attribute_handle_value_pair -> value

我发现了什么

每个attribute_handle_value_pair的值字段的大小是从其父级的长度字段派生的.我认为sizeof()方法首先尝试计算attribute_handle_value_pair的大小,而read_by_type_response的长度字段仍未定义,因此无法计算其大小.

我尝试将值字段的长度更改为静态值,并且效果很好.

我的问题

如何计算依赖于其父构造的构造的sizeof()?

我应该重新设计这个协议的建模方式吗?如果是这样呢?

解决方法

这在构造2.9中仍然是一个问题(2.8似乎没问题).

作为一种变通方法,您可以通过将子图的大小相加并直接传入长度来计算给定上下文的大小.

sum(sc.sizeof(length=4) for sc in AttReadByTypeResponse.subcons)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读