简体   繁体   English

如何从方法返回未知大小的字节数组

[英]How to return a byte array of unknown size from method

I have a class that parses some incoming serial data. 我有一个类解析一些传入的串行数据。 After the parsing a method should return a byte array with some of the parsed data. 解析后,方法应返回带有一些已解析数据的字节数组。 The incoming data is of unknown length so my return array will always be different. 传入的数据长度未知,因此我的返回数组将始终不同。

So far my method allocates an array bigger than what I need to return and fills it up with my data bytes and I keep an index so that I know how much data I put in the byte array. 到目前为止,我的方法分配了一个大于我需要返回的数组,并用我的数据字节填充它,并保留一个索引,以便我知道我在字节数组中放了多少数据。 My problem is that I don't know how to return this from an instance method. 我的问题是我不知道如何从实例方法返回它。

void HEXParser::getParsedData()
{
    byte data[HEX_PARSER_MAX_DATA_SIZE];
    int dataIndex = 0;

    // fetch data, do stuff
    // etc, etc...

    data[dataIndex] = incomingByte;
    _dataIndex++;

    // At the very end of the method I know that all the bytes I need to return
    // are stored in data, and the data size is dataIndex - 1
}

On other languages this is trivial to do but I'm not very proficient in C++ and I'm completely stuck. 在其他语言上这是微不足道的,但我不是很精通C ++而且我完全陷入困境。

Thanks! 谢谢!

You are working on a microcontroller with just a little bit of RAM. 您正在使用只需一点RAM的微控制器。 You need to carefully evaluate if "unknown length" also implies unbounded length. 您需要仔细评估“未知长度”是否也意味着无限长度。 You cannot deal with unbounded length. 你不能处理无限长度。 Your best approach for reliable operation is to use fixed buffers setup for the maximum size. 您可靠操作的最佳方法是使用固定缓冲区设置以获得最大尺寸。

A common pattern for this type of action is to pass the buffer to the function, and return what has been used. 此类操作的常见模式是将缓冲区传递给函数,并返回已使用的函数。 Your function would then look much like many of the C character string functions: 那么你的函数看起来很像C字符串函数:

const size_t HEX_PARSER_MAX_DATA_SIZE = 20;
byte data[HEX_PARSER_MAX_DATA_SIZE];

n = oHexP.getParsedData(data, HEX_PARSER_MAX_DATA_SIZE);

int HEXParser::getParsedData(byte* data, size_t sizeData)
{
  int dataIndex = 0;

  // fetch data, do stuff
  // etc, etc...

  data[dataIndex] = incomingByte;
  dataIndex++;
  if (dataIndex >= sizeData) {
     // stop
  }

  // At the very end of the method I know that all the bytes I need to return
  // are stored in data, and the data size is dataIndex - 1

  return dataIndex;
}

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

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