views:

254

answers:

3

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 ????

+1  A: 
const std::string s = icon();

const void *data=s.c_str();
Dave Gamble
+3  A: 

C++ strings represent the length explicitly, so they can contain binary data. You need to avoid passing the string to functions expecting a C-style string, since they won't handle embedded 0-chars.

unwind