基于Protobuf C++ serialize到char*的實(shí)現(xiàn)方法分析
protobuf的Demo程序是
C++版本的protubuf有幾種serialize和unSerialize的方法:
方法一:
官方demo程序采用的是
// Write the new address book back to disk.
fstream output(argv[1], ios::out | ios::trunc | ios::binary);
if (!address_book.SerializeToOstream(&output)) {
cerr << "Failed to write address book." << endl;
return -1;
}
// Read the existing address book.
fstream input(argv[1], ios::in | ios::binary);
if (!input) {
cout << argv[1] << ": File not found. Creating a new file." << endl;
} else if (!address_book.ParseFromIstream(&input)) {
cerr << "Failed to parse address book." << endl;
return -1;
}
上面采用的是fstream,把數(shù)據(jù)序列(反序列)打磁盤(pán)文件中。
而如果想序列到char *,并且通過(guò)socket傳輸,則可以使用:
方法二:
int size = address_book.ByteSize();
void *buffer = malloc(size);
address_book.SerializeToArray(buffer, size);
方法三:
使用ostringstream ,
std::ostringstream stream;
address_book.SerializeToOstream(&stream);
string text = stream.str();
char* ctext = string.c_str();
相關(guān)文章
淺析char 指針變量char *=p 這個(gè)語(yǔ)句的輸出問(wèn)題
下面小編就為大家?guī)?lái)一篇淺析char 指針變量char *=p 這個(gè)語(yǔ)句的輸出問(wèn)題。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-05-05基于C++實(shí)現(xiàn)柏林噪聲算法(Perlin?Noise)
Perlin噪聲(Perlin?noise,又稱(chēng)為柏林噪聲)指由Ken?Perlin發(fā)明的自然噪聲生成算法,具有在函數(shù)上的連續(xù)性,并可在多次調(diào)用時(shí)給出一致的數(shù)值。本文將用C++實(shí)現(xiàn)柏林噪聲算法,感興趣的可以了解一下2023-03-03C++實(shí)現(xiàn)四則混合運(yùn)算計(jì)算器
這篇文章主要為大家詳細(xì)介紹了C++實(shí)現(xiàn)四則混合運(yùn)算計(jì)算器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-11-11Pipes實(shí)現(xiàn)LeetCode(192.單詞頻率)
這篇文章主要介紹了Pipes實(shí)現(xiàn)LeetCode(192.單詞頻率),本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08C語(yǔ)言實(shí)現(xiàn)圖書(shū)管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了C語(yǔ)言實(shí)現(xiàn)圖書(shū)管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01