2013-11-26 59 views
2

的載體在我的C++應用程序,我有這樣的結構轉換一個結構的字節

typedef struct 
{ 
int a; 
int b; 
char *c 
}MyStruct 

,我有這樣的實例:

MyStruct s; 

我也有這樣的定義:

vector<byte> buffer; 

我想插入\將「s」結構轉換成緩衝區向量。

什麼是最好的方式來做到這一點在c + +?

感謝

+1

'vector buffer(sizeof(s)); memcpy(&buffer [0]&s,sizeof(s));' –

+4

你想要做序列化嗎?你關心排序嗎?填充?對準? –

+0

和你想用你的'char * c'做什麼?你應該複製它的內容嗎?順便說一句,你的代碼看起來不像C++ –

回答

8

,最好的辦法是使用range copy constructor和低層次的投檢索指針結構的內存:

auto ptr = reinterpret_cast<byte*>(&s); 
auto buffer = vector<byte>{ptr, ptr + sizeof(s)}; 

爲了走另一條路,你可以投字節緩衝區爲目標類型(但它需要是相同類型,否則你違反strict aliasing):

auto p_obj = reinterpret_cast<obj_t*>(&buffer[0]); 

但是,對於索引≠0(我猜在技術上也適用於索引= 0,但這似乎不太合理),請注意不匹配memory alignment。因此,更安全的方法是首先將緩衝區複製到properly aligned storage,並從那裏訪問指針。

+0

很好的答案。我有一個不同的問題:我需要做「其他的方式」:我有一個向量,它充滿了值(它的大小是100),我想比較的前8個字節具有給定結構的矢量,其定義如下: \t struct BlockInfoHeader \t { \t \t uint32_t magicHeader; \t \t uint32_t thread; \t \t uint64_t timestamp; //開始運行後的微秒數 \t \t uint64_t offset; \t \t uint32_t len; \t \t uint32_t blockIndex; \t \t uint32_t writeIndex; \t \t uint32_t seed; \t};爲了比較向量的前8個字節與預先給定的某些值。 –

+1

@GuyAvraham查看更新。 –

相關問題