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

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

我希望能够使用 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 doc:

SerializeToString(string* output) const;

serializes the message and stores the bytes in the given string. Note that the bytes are binary, not text; we only use the string class as a convenient container.

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

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