基于Protobuf C++ serialize到char*的實現(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ù)序列(反序列)打磁盤文件中。
而如果想序列到char *,并且通過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)文章
基于C++實現(xiàn)柏林噪聲算法(Perlin?Noise)
Perlin噪聲(Perlin?noise,又稱為柏林噪聲)指由Ken?Perlin發(fā)明的自然噪聲生成算法,具有在函數(shù)上的連續(xù)性,并可在多次調(diào)用時給出一致的數(shù)值。本文將用C++實現(xiàn)柏林噪聲算法,感興趣的可以了解一下2023-03-03Pipes實現(xiàn)LeetCode(192.單詞頻率)
這篇文章主要介紹了Pipes實現(xiàn)LeetCode(192.單詞頻率),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-08-08