c++ - Google Protocol Buffer 序列化字符串可以包含嵌入的 NULL 字符吗?

标签 c++ serialization null protocol-buffers stdstring

我正在使用 Google Protocol Buffer 进行消息序列化。 这是我的示例原型(prototype)文件内容。

package MessageParam;

message Sample
{
    message WordRec
    {
        optional uint64 id = 1; 
        optional string word = 2;
        optional double value = 3;
    }
    message WordSequence
    {
        repeated WordRec WordSeq = 1;
    }
}

我正在尝试用 C++ 序列化消息,如下所示

MessageParam::Sample::WordSequence wordseq;
for(int i =0;i<10;i++)
{
    AddRecords(wordseq.add_wordseq());
}
std::string str = wordseq.SerializeAsString();

执行上述语句后,str的大小为430。它嵌入了空字符。当我尝试将此 str 分配给 std::wstring 时,std::wstring 在找到第一个空字符时终止。

void AddRecords(MessageParam::Sample::WordRec* wordrec)
{
    int id;
    cin>>id;
    wordrec->set_id(id);
    getline(cin, *wordrec->mutable_word());
    long value;
    cin>>value;
    wordrec->set_value(value);
}

wordseq.DebugString() 的值为 WordSeq { 编号:4 词语:“软件” 值:1 } 词序{ 编号:19 词语:“技术” 值:0.70992374420166016 } 词序{ 编号:51 词语:“硬件” 值:0.626017153263092 } 如何将“wordseq”序列化为包含嵌入 NULL 字符的字符串?

最佳答案

您不应该尝试将 Protobuf 存储在 wstring 中。 wstring用于存储 unicode 文本,但 protobuf 不是 unicode 文本或任何其他类型的文本,它是原始字节。您应该以字节形式保存。如果您确实需要在文本上下文中存储 Protobuf,您应该首先对其进行 Base64 编码。

可以说 Protobufs 对 std::string 的使用存储字节(而不是文本)是令人困惑的。也许它应该使用 std::vector<unsigned char>一直。你应该对待 protobufs' std::string就像你想的那样std::vector<unsigned char> .

关于c++ - Google Protocol Buffer 序列化字符串可以包含嵌入的 NULL 字符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30365373/

相关文章:

JAVA:为什么我的主机和帖子在其他类中返回 null

c# - 一次反序列化json数组流一项

c++ - 类成员是另一个类的对象

c++ - 高效使用python对象迭代大量数据调用python函数

指针返回问题的 c++ 协方差问题

c# - 通过网络发送自定义结构 - SerializationException

c++用std::string读写结构数组到二进制文件

带有NULL列的SQL联接

c - 从mmaped NULL指针读取数据

c++ - 段错误重载运算符 <<