带有Protobuf序列化的C++Hazelcast:字符串不是UTF-8格式的

C++ Hazelcast with Protobuf serialization: String is not UTF-8 formatted

本文关键字:UTF-8 格式 字符串 Protobuf 序列化 C++Hazelcast 带有      更新时间:2023-10-16

我希望能够使用HazelCast发送序列化的Protobuf数据。我理解为什么它会给我错误,但有办法解决吗?

这是我正在使用的示例代码:

main.cpp

#include <iostream>
#include <vector>
#include <hazelcast/client/HazelcastClient.h>
#include "testProto.pb.h"
using namespace std;
int main(){
// create object
tutorial::Input protoInput;
protoInput.set_innum(500);
// buffer to store serialized string
string stringBuffer;
protoInputer.SerializeToString(&stringBuffer);


// set up hazelcast client
hazelcast::client::ClientConfig(config);
hazelcast::client::HazelcastClient hz(config);
hazelcast::client::IMap<string,string> map = hz.getMap<string,string>("myMap");

//error is from trying to write it
map.put("Input", stringBuffer);
return 0;
}

testProto.proto

syntax = "proto3";
package tutorial;
message Input{
int64 inNum = 1;
}

来自protobuf文档:

SerializeToString(string*输出(常量;

序列化消息并将字节存储在给定字符串中。请注意,字节是二进制的,而不是文本;我们只使用字符串类作为一个方便的容器。

因此,将它们作为字符串存储在IMap中是不安全的,因为在非UTF-8格式的情况下很容易失败。我建议您将protobuf存储为字节向量,其中hazelcast::byteunsigned char:

hz.getMap<string, vector<hazelcast::byte>>("proto_map");