ParseFromArray Returns false

5,098 views
Skip to first unread message

Jean-Sebastien Stoezel

unread,
Jul 23, 2008, 4:12:53 PM7/23/08
to Protocol Buffers
Hello,

It looks like whenever I call ParseFromArray it returns false, even if
the message seems to properly be set...

Here is a code example to illustrate the issue:

#include <iostream>
#include "iceDetection.pb.h"

using namespace std;

int main(int argc, char *argv[])
{
char buffer[4*1024];

cout << "ProtoBuf Eval";

iceData my_IceDataSent;
iceData my_IceDataReceived;

my_IceDataSent.set_avgthickness(1.23);
my_IceDataSent.set_maxthickness(2.23);
my_IceDataSent.set_minthickness(0.23);

cout << "This is what I sent: avgthickness=" <<
my_IceDataSent.avgthickness() << " maxthickness=" <<
my_IceDataSent.maxthickness() << " minthickness=" <<
my_IceDataSent.minthickness();

memset(buffer, 0, sizeof(buffer));
if(true == my_IceDataSent.SerializeToArray(buffer, sizeof(buffer)))
{
cout << "\nSerialization succeeded";
if(true == my_IceDataReceived.ParseFromArray(buffer, sizeof(buffer)))
{
cout << "\nParsing succeeded";
cout << "This is what I received: avgthickness=" <<
my_IceDataReceived.avgthickness() << " maxthickness=" <<
my_IceDataReceived.maxthickness() << " minthickness=" <<
my_IceDataReceived.minthickness();
}
else
{
cout << "\nParsing failed";
}
}
else
{
cout << "\nSerialization failed";
}

return 0;
} // main

ParseFromArray always returns false, however my_IceDataReceived seems
to contain the values encoded in my_IceDataSent.

Any ideas?

Thanks!

Kenton Varda

unread,
Jul 23, 2008, 4:26:47 PM7/23/08
to Jean-Sebastien Stoezel, Protocol Buffers
When you use ParseFromArray(), you need to pass it the exact size of the message, because protocol buffers are not self-delimiting.  In your code, you're passing in a butter that is much larger than the actual message and has a lot of uninitialized bytes at the end.  The parser will attempt to parse these bytes and fail, hence what you're seeing.

You can determine the size of a message when you serialize it by calling the ByteSize() method.

Jean-Sebastien Stoezel

unread,
Jul 23, 2008, 4:49:15 PM7/23/08
to Kenton Varda, Protocol Buffers
Sorry I meant SerializeToArray instead of ParseFromArray

On 7/23/08, Jean-Sebastien Stoezel <js.st...@gmail.com> wrote:
> Hi,
>
> when calling ParseFromArray, why pass the size of the object as an
> argument then, since it looks like this will always be whatever
> ByteSize() returns (please correct me if I'm wrong). Can't ByteSize()
> be access from within ParseFromArray()?

Kenton Varda

unread,
Jul 23, 2008, 5:18:21 PM7/23/08
to Jean-Sebastien Stoezel, Protocol Buffers
The only reason is to avoid accidental buffer overruns.
Reply all
Reply to author
Forward
0 new messages