簡體   English   中英

如何使用Google協議緩沖區序列化為char *?

[英]How to serialize to char* using Google Protocol Buffers?

我想將協議緩沖區序列化為char *。 這可能嗎? 我知道一個可以序列化為文件如下:

fstream output("/home/eamorr/test.bin", ios::out | ios::trunc | ios::binary);
if (!address_book.SerializeToOstream(&output)) {
  cerr << "Failed to write address book." << endl;
  return -1;
}

但我想序列化為C樣式的char *以便通過網絡進行傳輸。

這該怎么做? 請記住,我是C ++的新手。

這很簡單:

size_t size = address_book.ByteSizeLong(); 
void *buffer = malloc(size);
address_book.SerializeToArray(buffer, size);

還要檢查MessageLite類的文檔 ,它是Message的父類,並且包含有用的方法。

您可以將輸出序列化到ostringstream並使用stream.str()獲取字符串,然后使用string.c_str()訪問c字符串。

std::ostringstream stream;
address_book.SerializeToOstream(&stream);

string text = stream.str();
char* ctext = text.c_str();

不要忘記為std::ostringstream包括sstream

您可以使用ByteSizeLong()獲取消息將占用的字節數,然后使用SerializeToArray()用編碼后的消息填充數組。

還有一行代碼可以照顧到序列化數據可以包含零的事實。

std::ostringstream stream;
address_book.SerializeToOstream(&stream);

string text = stream.str();
char* ctext = text.c_str();    // ptr to serialized data buffer
//  strlen(ctext) would wrongly stop at the 1st 0 it encounters.
int   data_len = text.size();  // length of serialized data

使用數組智能指針的解決方案:

size_t size = address_book.ByteSizeLong();
std::unique_ptr<char[]> serialized(new char[size]);
address_book.SerializeToArray(&serialized[0], static_cast<int>(size));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM