Using Protocol Buffers to send icons/small images
-
12-09-2019 - |
Question
I have a simple question about std::string and google's protocol buffers library. I have defined a message like so:
message Source
{
required string Name = 1;
required uint32 Id = 2;
optional string ImplementationDLL = 3;
optional bytes Icon = 4;
}
I want to use the Icon field to send an image, it most probably will be a png image. After feeding this to the protobuf compiler i got something like this to access/manipulate the Icon field.
inline bool has_icon() const;
inline void clear_icon();
static const int kIconFieldNumber = 4;
inline const ::std::string& icon() const;
inline void set_icon(const ::std::string& value);
inline void set_icon(const char* value);
inline void set_icon(const void* value, size_t size);
inline ::std::string* mutable_icon();
the std::string* mutable_icon() function is giving me a headache. It is returning a std::string but i believe strings can not hold binary data ! or can they ?
i can use set_icon(const void*, size_t) function to put binary data, but then how do i get it on the other side ?
i think std::string might be able to hold binary data, but how ????
Solution 3
the answer to this question: How do you construct a std::string with an embedded null?
OTHER TIPS
const std::string s = icon();
const void *data=s.c_str();
C++ strings represent the length explicitly, so they can contain binary data, including the 0-character that terminates C strings.
You need to avoid passing the string to functions expecting a C-style string, since they won't handle embedded 0-chars.
void String2Image(string binFile,const char* outImage)
{
fstream imgFile(outImage,ios::binary|ios::out);
for(int i=0; i<binFile.length(); ++i)
{
imgFile << binFile[i];
}
imgFile.close();
}