简体   繁体   中英

Converting Python ProtoBuf to C++ ProtoBuf using SerializeToString() and ParseFromString() functions

Hi I've a simple example of addressbook.proto I am serializing using the protobuf SerailizeToString() function in python . Here's the code.

import address_pb2

person = address_pb2.Person()
person.id = 1234
person.name = "John Doe"
person.email = "jdoe@example.com"
phone = person.phones.add()
phone.number = "555-4321"
phone.type = address_pb2.Person.HOME

print(person.SerializeToString())

Where address_pb2 is the file I generated from the protobuf compiler. Note that the example is copied from the protoBuf tutorials. This gives me the following string.

b'\n\x08John Doe\x10\xd2\t\x1a\x10jdoe@example.com"\x0c\n\x08555-4321\x10\x01'

Now I want to import this string into c++ protobuf. For this I wrote the following code.

#include <iostream>
#include <fstream>
#include <string>
#include "address.pb.h"
using namespace std;

int main(int argc, char* argv[]) {
  GOOGLE_PROTOBUF_VERIFY_VERSION;


  tutorial::AddressBook address_book;
  string data = "\n\x08""John Doe\x10""\xd2""\t\x1a""\x10""jdoe@example.com\"\x0c""\n\x08""555-4321\x10""\x01""";
  if(address_book.ParseFromString(data)){
    cout<<"working"<< endl;
  }
  else{
    cout<<"not working" << endl;
  }


  // Optional:  Delete all global objects allocated by libprotobuf.
  google::protobuf::ShutdownProtobufLibrary();

  return 0;
}

Here I am simply trying to import the script using ParseFromString() fucntion but this doesn't work and I am not sure how it will work as I've been stuck on this since a long time now.

I tried changing the binary a bit to suit the c++ version but still no idea if I am on the right path or not.

How can I achieve this ? Does anybody have a clue ?

In Python, you are serializing a Person object. In C++, you are trying to parse an AddressBook object. You need to use the same type on both ends.

(Note that protobuf does NOT guarantee that it will detect these errors. Sometimes when you parse a message as the wrong type, the parse will appear to succeed, but the content will be garbage.)


There's another issue with your code that happens not to be a problem in this specific case, but wouldn't work in general:

string data = "\n\x08""John Doe\x10""\xd2""\t\x1a""\x10""jdoe@example.com\"\x0c""\n\x08""555-4321\x10""\x01""";

This line won't work if the string has any NUL bytes, ie '\\x00'. If so, that byte would be interpreted as the end of the string. To avoid this problem you need to specify the length of the data, like:

string data("\n\x08""John Doe\x10""\xd2""\t\x1a""\x10""jdoe@example.com\"\x0c""\n\x08""555-4321\x10""\x01""", 45);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM