Reputation: 65
I am trying to serialize the message as string in C++ using google protocol buffer and assign the serialized result (which contains embedded nulls in it) to std::string. Following is my code:
std::string result = message.SerializeAsString();
It is ignoring the characters after the first \0 character. result is not having the full serialized string. I tried the following which explicitly specifies the length.
int size = message.ByteSize();
std::string result(std::string(message.SerializeAsString()), size);
It is also not working for me. Is there any other way to do this ?
Thanks in advance.
Upvotes: 1
Views: 3904
Reputation: 45181
There is no problem storing NUL bytes in std::strings. You can just assign the string normally. Both of your code snippets should work fine.
The problem comes if you ever call .c_str()
and try to pass the string to something expecting const char*
. At this point, the receiver of the const char*
doesn't know the size of the string so assumes it ends at the first NUL byte. So, don't do that -- always make sure you're either passing the std::string
whole, or that your passing both a pointer and a size (from .size()
).
You commented on another answer that you need to convert to std::wstring
. EDIT: I moved my comments on this to your other question.
Upvotes: 2
Reputation: 4835
std::string result(message.SerializeAsString(), size);
when you are creating the temporary string
std::string(message.SerializeAsString())
This part consumes the embedded nulls.
Upvotes: 1