5

I'm writing pybindngs for a C++ class that has Google Protobuf objects as member variables. I'd like these binded-functions to return (in Python land) the Python version of the protobuf object (which Google's proto compiler natively generates).

If I try and naively return the C++ version of the protobuf in the pybind definition

.def_readwrite("my_protobuf", &my_protobuf_)

, I get the following error:

TypeError: Unable to convert function return value to a Python type! The signature was
        (self: MyClass) -> MyProtobufDef

which makes sense - the return type is a C++ protobuf object, not the Python protobuf object. How do I convert this into the Python version of the protobuf?

  • All return C++ types must have python counterparts. You should bind your protobuf class via `pybind11::class_....` – Sergei May 26 '19 at 11:16
  • @Sergei - that means I must re-write Python bindings for all of my protobufs, which is less than desireable given that Protobuf automatically generates those for me. Is there a way for me to reuse the auto-generated protobuf classes? – user1848737 May 27 '19 at 20:36
  • 1
    pybind11 is about *bindings* of C++ objects. Protobuf is about *serialization* with available generators for many languages. If you want to use C++ objects via python you need *binding* library. If you need to serialize/send/deserialize objects you need a *serialization* library. If you want to have both you need two tools. If it's an option you may want to serialize object on python size and unpack on C++ side using protobuf only and vise versa. In principle automatic binding generation is possible, but I'm not aware of such library. – Sergei May 27 '19 at 20:54
  • @user1848737 was this problem solved eventually? – Johnzy Apr 21 '23 at 04:01

0 Answers0