【问题标题】:Python's construct - .sizeof() for construct depending on its parentPython 的构造 - .sizeof() 用于构造取决于其父级
【发布时间】:2017-11-28 13:18:58
【问题描述】:

这篇文章是关于 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_pairvalue 字段的大小派生自其父级的length 字段。我认为sizeof()方法是先计算attribute_handle_value_pair的大小,而read_by_type_responselength字段仍然未定义,因此无法计算其大小。

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

我的问题

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

我应该重新设计此协议的建模方式吗?如果是那怎么办?

【问题讨论】:

  • 看起来像是循环依赖问题,而不是父/子评估。文档 do 请注意,结构使用可变大小数组的情况可能会触发 SizeofError - construct.readthedocs.io/en/latest/…
  • 我是 Construct 开发者。没有循环依赖。这应该可以正常工作。
  • d = Struct("length" / Int8ub, "data" / Bytes(this.length), ) d.sizeof()construct.core.SizeofError: 无法计算大小,在上下文中找不到键你能分享一下修复 SizeofError 的代码 sn-p 吗

标签: python parsing construct


【解决方案1】:

目前这在 Construct 2.9/2.10 中仍然是一个问题(2.8 似乎没问题)。

作为一种解决方法,您可以通过对子控件的大小求和并直接传递长度来计算给定上下文的大小。

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

如果您使用新的编译结构功能,则需要使用defersubcon 访问原始结构。

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

【讨论】:

    猜你喜欢
    • 2010-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多