简体   繁体   English

nanopb : 获取重复子消息的大小

[英]nanopb : get the size of repeated submessages

For a project, I'm trying to decode a repeated number of structs, which I have to fill into a dynamically allocated array, but for this to work, I need to know how many elements the repeated submessage has, in order to allocate the right size beforehand.对于一个项目,我正在尝试解码重复数量的结构,我必须将其填充到动态分配的数组中,但为了使其工作,我需要知道重复的子消息有多少元素,以便分配事先合适的尺寸。 I'm working with a variable size for the repeated submessages (with no upper limit), so I can't use max_size .我正在为重复的子消息使用可变大小(没有上限),所以我不能使用max_size

But I can't seem to find any way to retrieve the number of submessages beforehand.但我似乎找不到任何方法来事先检索子消息的数量。

So, does anybody know how to find out the number of submessages in a repeated field?那么,有人知道如何找出重复字段中子消息的数量吗?

My only other option I can think of, is to temporarily use a linked list to keep track of all the information, and then after decoding copying the information into an array, but that seems very cumbersome and dirty.我能想到的唯一其他选择是暂时使用链表来跟踪所有信息,然后在解码后将信息复制到数组中,但这似乎非常麻烦和肮脏。

Nanopb by itself optionally supports dynamic allocation, which uses realloc() to incrementally expand the allocated array. Nanopb 本身可选地支持动态分配,它使用realloc()来增量扩展分配的数组。 To use this, you would define [(nanopb).type = FT_POINTER] in the .proto , and use PB_ENABLE_MALLOC compiler define.要使用它,您将在 .proto 中定义[(nanopb).type = FT_POINTER] .proto并使用PB_ENABLE_MALLOC编译器定义。

If you want to count the number of items in the repeated field beforehand, you could use a field callback.如果要预先计算repeated字段中的项目数,可以使用字段回调。 Then you could replace the callback with a different one that stores the items in the array and decode the message again.然后,您可以将回调替换为将项目存储在数组中并再次解码消息的不同回调。 Ideally though you could process the data directly in the callback, instead of storing it to RAM in between.理想情况下,您可以直接在回调中处理数据,而不是将其存储到 RAM 中。

However, if this is a memory constrained embedded system (which is what nanopb mainly targets), I would suggest just deciding a reasonable maximum and setting max_size to it.但是,如果这是一个内存受限的嵌入式系统(这是 nanopb 的主要目标),我建议只确定一个合理的最大值并将max_size设置为它。 That way if you run out of memory, it will be immediately apparent in testing as the maximum needed amount is always allocated.这样,如果你的内存用完了,它会在测试中立即显现出来,因为总是分配了最大需要的数量。 On systems with small amounts of RAM, you cannot assume that dynamic allocation will predictably succeed.在具有少量 RAM 的系统上,您不能假设动态分配会成功。 Effects such as memory fragmentation can cause allocations to fail depending on what sequence of allocations has been previously performed.内存碎片等影响可能会导致分配失败,具体取决于先前执行的分配顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM