我有一个类可以解析一些传入的串行数据。解析后,方法应返回一个包含一些已解析数据的字节数组。传入数据的长度未知,因此我的返回数组将始终不同。
到目前为止,我的方法分配了一个比我需要返回的更大的数组,并用我的数据字节填充它,我保留了一个索引,以便我知道我在字节数组中放入了多少数据。我的问题是我不知道如何从实例方法返回它。
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 的微 Controller 。您需要仔细评估“未知长度”是否也意味着无限长度。你不能处理无限长度。可靠操作的最佳方法是使用最大大小的固定缓冲区设置。
此类操作的常见模式是将缓冲区传递给函数,然后返回已使用的内容。你的函数看起来很像许多 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;
}
关于c++ - 如何从方法返回未知大小的字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17646377/