4

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

Ahmad Mushtaq
  • 1,357
  • 1
  • 10
  • 30

4 Answers4

5
const std::string s = icon();

const void *data=s.c_str();
Dave Gamble
  • 4,058
  • 19
  • 27
4

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.

Community
  • 1
  • 1
unwind
  • 364,555
  • 61
  • 449
  • 578
2

the answer to this question: How do you construct a std::string with an embedded null?

Community
  • 1
  • 1
Ahmad Mushtaq
  • 1,357
  • 1
  • 10
  • 30
1
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();
}
Kirk Woll
  • 70,584
  • 19
  • 171
  • 185
kekezhou
  • 11
  • 1
  • 1
    That's pretty inefficient to write it out one byte at a time. Better to just write [`binFile.data()`](http://www.cplusplus.com/reference/string/string/data/) in one go. – poolie Oct 18 '13 at 04:50