简体   繁体   中英

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.

Thanks!

You are working on a microcontroller with just a little bit of 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:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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