【发布时间】:2017-03-07 09:55:00
【问题描述】:
我有一个二进制数据缓冲区,我想将它存储在协议缓冲区中。
在文档 (https://developers.google.com/protocol-buffers/docs/proto#scalar) 中,它说 bytes 类型等同于 C++ 中的 string。我简直不敢相信,所以我不得不尝试一下,是的,这似乎是这样..
这个原型:
message BufferMsg {
required bytes buffer = 1;
}
给出一个包含以下内容的消息定义:
private:
::std::string* buffer_;
公共 setter/getter API 如下所示:
// required bytes buffer = 1;
inline bool has_buffer() const;
inline void clear_buffer();
static const int kBufferFieldNumber = 1;
inline const ::std::string& buffer() const;
inline void set_buffer(const ::std::string& value);
inline void set_buffer(const char* value);
inline void set_buffer(const void* value, size_t size);
inline ::std::string* mutable_buffer();
inline ::std::string* release_buffer();
inline void set_allocated_buffer(::std::string* buffer);
当然,这不可能是在消息中存储二进制数据的方式。应该怎么做?在 C++ 中,我通常会使用 unsigned char 数组或类似的东西来存储数据。
【问题讨论】:
-
“当然,这不可能是在消息中存储二进制数据的方式。应该怎么做?” 您有什么顾虑?我用过,效果很好。
-
在
std::string中存储零没有问题吗? -
不,将
'\0'存储在std::string中从来没有问题。长度是独立跟踪的。
标签: c++ protocol-buffers