Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python, how do I get a binary serialization of my Google protobuf message?

I see the function SerializeAsString in the protobuf Python documentation, but like this suggests, this gives me a string version of the binary data. Is there a way of serializing and parsing a binary array of protobuf data using Python?

We have a C++ application that stores the protobuf messages as binary data in a file. We'd like to read and write to the file using Python.

like image 324
Nick Bolton Avatar asked Jan 22 '23 21:01

Nick Bolton


2 Answers

Python strings can hold binary data, therefore SerializeAsString returns binary data.

like image 136
Nick Bolton Avatar answered Jan 31 '23 20:01

Nick Bolton


.serializeToString(), despite its name, returns the bytes type, not the str type.

Part of what makes this confusing is that the method name remains unchanged, and they haven't updated the documentation; you just have to know that when they say "String" they mean bytes.

like image 26
rspeer Avatar answered Jan 31 '23 20:01

rspeer