基于Protobuf C++ serialize到char*的實現方法分析
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,把數據序列(反序列)打磁盤文件中。
而如果想序列到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();
相關文章
C語言詳解關鍵字sizeof與unsigned及signed的用法
這篇文章主要為大家詳細介紹了C語言關鍵字sizeof&&unsigned&&signed,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-06-06
Visual?Studio?2022下載及配置OpenCV4.5.5的詳細過程
這篇文章主要介紹了Visual?Studio?2022下載及配置OpenCV4.5.5的詳細過程,在這里注意下Win10的64位操作系統,在OpenCV官網下載OpenCV4.5.5,安裝的是Win?pack,本文通過圖文并茂的形式給大家介紹的非常詳細,需要的朋友可以參考下2022-05-05

