[英]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.