I ParseFromArray the protocol buffer's protocol, the protocol is not lack any filed. But the ParseFromArray function returns false
. Why?
Asked
Active
Viewed 1.4k times
4

BenMorel
- 34,448
- 50
- 182
- 322

user2231794
- 51
- 1
- 1
- 5
-
You might want to add a language Tag (e.g. Java, c# etc) because there different versions of protocol buffers for different languages. Also some languages have several different versions of Protocol Buffers – Bruce Martin Nov 08 '13 at 21:55
1 Answers
11
I'm assuming you are using C++. ParseFromArray()
fails if:
- The input data is not in valid protobuf format.
- The input data is lacking a required field.
If you are sure that all required fields are set, then it must be the case that your input data is corrupted. You should verify that the bytes and size you are passing into ParseFromArray()
are exactly the bytes and size that you got from SerializeToArray()
and ByteSize()
on the sending side. You will probably find that you are losing some bytes somewhere, or that some bytes got corrupted.
Common reasons for corruption include:
- Passing the encoded bytes over a text-only channel. E.g. if you write the data to (or read it from) a file that is not opened in "binary" mode, or if you at some point store the bytes in a Java
String
, the data will become corrupted, as these channels expect text, and encoded protobufs are not text. - Passing the bytes as a
char*
, i.e. assuming NUL-termination. Encoded protobufs can contain'\0'
bytes, meaning that you cannot represent one as achar*
alone -- you must include the size separately. - Serializing to an array that is larger than needed, and then forgetting to pay attention to how much data was actually written. When you call
SerializeToArray()
, you must also callByteSize()
to see how large the message is, and you must make sure the receiving end receives that size and passes it toParseFromArray()
. Otherwise, the parser will think that the extra bytes at the end of the buffer are part of the message, and will fail to parse them.

Kenton Varda
- 41,353
- 8
- 121
- 105
-
2A special case when input data lacks a required field occurs while **parsing a required enum field with an incorrect value**. According to the [doc](https://developers.google.com/protocol-buffers/docs/reference/cpp-generated#enum), if an invalid enum value is read when parsing a message, it will be treated as an unknown field. In turn, an invalid enum value can be passed through the wire if the sender has a different version of the enumeration definition in it's proto-file, say sender's enum has several additional values compared to the receiver. – Alex Che Feb 23 '15 at 14:40