| 63 | */ |
| 64 | template <typename T> |
| 65 | bool readPythonProtobuf(PyObject* obj, T* t) |
| 66 | { |
| 67 | if (obj == Py_None) { |
| 68 | std::cerr << "None object given where protobuf expected" << std::endl; |
| 69 | return false; |
| 70 | } |
| 71 | PyObject* res = PyObject_CallMethod(obj, |
| 72 | (char*) "SerializeToString", |
| 73 | (char*) nullptr); |
| 74 | if (res == nullptr) { |
| 75 | std::cerr << "Failed to call Python object's SerializeToString " |
| 76 | << "(perhaps it is not a protobuf?)" << std::endl; |
| 77 | PyErr_Print(); |
| 78 | return false; |
| 79 | } |
| 80 | char* chars; |
| 81 | Py_ssize_t len; |
| 82 | if (PyString_AsStringAndSize(res, &chars, &len) < 0) { |
| 83 | std::cerr << "SerializeToString did not return a string" << std::endl; |
| 84 | PyErr_Print(); |
| 85 | Py_DECREF(res); |
| 86 | return false; |
| 87 | } |
| 88 | google::protobuf::io::ArrayInputStream stream(chars, len); |
| 89 | bool success = t->ParseFromZeroCopyStream(&stream); |
| 90 | if (!success) { |
| 91 | std::cerr << "Could not deserialize protobuf as expected type" << std::endl; |
| 92 | } |
| 93 | Py_DECREF(res); |
| 94 | return success; |
| 95 | } |
| 96 | |
| 97 | |
| 98 | /** |
no outgoing calls
no test coverage detected