簡體   English   中英

如何從方法返回未知大小的字節數組

[英]How to return a byte array of unknown size from 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
}

在其他語言上這是微不足道的,但我不是很精通C ++而且我完全陷入困境。

謝謝!

您正在使用只需一點RAM的微控制器。 您需要仔細評估“未知長度”是否也意味着無限長度。 你不能處理無限長度。 您可靠操作的最佳方法是使用固定緩沖區設置以獲得最大尺寸。

此類操作的常見模式是將緩沖區傳遞給函數,並返回已使用的函數。 那么你的函數看起來很像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