2013-07-15 91 views
0

我有一個類來解析一些傳入的串行數據。解析一個方法後,應該返回一個帶有一些解析數據的字節數組。傳入的數據長度未知,所以我的返回數組將始終不同。如何從方法返回未知大小的字節數組

到目前爲止,我的方法分配一個比我需要返回的數組大的數組,並用我的數據字節填充它,並且保留一個索引,以便我知道我在字節數組中放置了多少數據。我的問題是,我不知道如何從實例方法返回此。

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++,我完全卡住了。

謝謝!

+3

使用['std :: vector'](http://en.cppreference.com/w/cpp/container/vector)。 –

+0

'數據'應該動態分配,如果你想返回它 –

+1

ahhhhh,而不是在微控制器上。離開堆。 – jdr5ca

回答

2

您正在使用只有一點點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; 
} 
+0

+1:允許調用者處理分配在perf-conscious代碼使用的API中非常讚賞。 –

+0

謝謝,這個作品非常好! – Julian