python-3.xcastingtype-conversionprotocol-buffersmessaging

Google Protobuf without deserialization


Normally, google protobuf or the nanopb implementation is intended to serialize/deserialize messages on the server/client side respectively.

However, I'm faced with a case where the serialization has been omitted on the server side, because somebody wanted to optimize it away (Probably relying on the byteorder being the same on client/server).

On the client side, I like to deserialize the messages, which fails for the said reason. I receive a byte array from the server, but this byte array is just a cast of the original message to an array of bytes.

Now, I'm not able to set-up a google.protobuf.message from the byte array, because I cannot call ParseFromString on the cast. What I need is something like the int.from_bytes method but for protobuf messages.

Say, I have a message xx_pb2.MYMESSAGE in the protoc generated source file xx_pb2. I want to convert the byte array into this message (Pseudocode: xx_pb2.MYMESSAGE.from_bytes(the_byte_array)).

How can I do this?


Solution

  • Here's what I'd do: