protobuf in C++ with dynamic binding for google::protobuf::M
protobuf in C++ with dynamic binding for google::protobuf::Message
在C++中使用protobuf,我有一系列消息将共享一对编码和解码自定义API,例如Pack((和Unpack((;
但我很快意识到,我必须对消息类型进行硬编码,以便能够将数据从流解码为正确的数据结构。
由于不支持继承,因此我随后查看了Any
设施。但是,官方文档太简洁了,无法用工作示例指导我。
我想确认 Any 是否像这样工作:
假设我需要从解码器端的工厂创建一些消息类型,那么......
步骤#1:我必须像这样定义我的proto3
syntax = "proto3";
import "google/protobuf/any.proto";
message Envelope {
google.protobuf.Any actual_msg = 1;
string id = 2;
}
message PublicProfile {
string name = 1;
int32 age = 2;
bool isMale = 3;
}
message PrivateProfile {
string nickname = 1;
int32 money = 2;
}
第 2 步:编码器将像这样工作
//encoder.cpp
Envelope payload;
payload.set_id("my.com/msg/profile.public");
PublicProfile pp;
pp.name = "Tom";
pp.age = 30;
pp.isMale = true;
payload.get_actual_msg().PackFrom(pp); // NOT Sure how to use PackFrom at all!
int pakSize = payload.ByteSize()
std::string packet(pakSize, ' ');
google::protobuf::io::ArrayOutputStream aos((void*)packet.c_str(), pakSize);
google::protobuf::io::CodedOutputStream* cos = new google::protobuf::io::CodedOutputStream(&aos);
payload.SerializeToCodedStream(cos);
步骤#3:最后解码器需要
// decoder.cpp
Envelope payload;
google::protobuf::io::ArrayInputStream ais(packet.c_str(), packet.size());
google::protobuf::io::CodedInputStream cis(&ais);
payload->ParseFromCodedStream(&cis);
google::protobuf::Any actual_msg = payload.actual_msg();
if (payload.id() == "my.com/msg/profile.public") {
PublicProfile pp;
actual_msg.UnpackTo(&pp);
}
它以这种方式工作吗?
由于没有人愿意回答,我报告我自己的发现。
我们不需要协议中的显式 ID。Any
内置了一个ID,由Protobuf自动生成。
解码时,只需调用指定的方法从Any
对象中检索 ID,我们就可以自由地将其与任何自定义模式进行匹配
myAnyMsg.type_url()
典型的网址如下所示
type.googleapis.com/<message_type_defined_in_proto>
相关文章:
- Google protobuf 时间戳未声明标识符,在 Windows 上具有C++
- CMake 在编译 Google 的 protobuf 示例时找不到 protobuf
- E/libc++abi:终止于类型为google::protobuf::FatalException的未捕获异常
- protobuf in C++ with dynamic binding for google::protobuf::M
- 将 TensorFlow 链接到C++.Protobuf (/usr/local/include/google/prot
- Google protobuf and Android NDK
- 防止客户端套接字程序崩溃CPP Google Protobuf
- Google的protobuf版本是用-std=c++98或-std=c++03构建的?
- 致命错误:google/protobuf/port_def.inc:没有这样的文件或目录 #include < google/protobuf/port_def.inc>
- 静态地将Google Protobuf lib链接到DLL库中
- 对Google :: Protobuf的未定义引用在ROS CPP中
- Google Protobuf 3:使用 CMAKE 构建时未定义的引用错误
- 通过Google Protobuf发送二进制文件数据
- 对Google :: ProtoBuf :: Internal :: empty_string_ [abi:cxx11]
- Google的protobuf库中的MergeFrom* vs. ParseFrom*
- Google Protobuf基于C++的python实现的性能
- Google protobuf在解析字符串数据时在Android中崩溃
- C++Protobuf错误google::Protobuf::internal::kEmptyString错误
- 如何使用Google Protobuf实现地图结构
- 带有协议缓冲区的程序无法使用 MinGW-w64 编译:"undefined reference to google::protobuf:: ..."