我在小型系统上使用 protobuf-embedded-c将不同的数据从它传输到PC.问题是,如果我在两端都使用嵌入式库,一切正常.如果我在PC上使用谷歌C它不再工作.我想我将问题追溯到每个消息中都有长
person.proto:
enum PhoneType { MOBILE = 0; HOME = 1; WORK = 2; } message PhoneNumber { required float number = 1; required PhoneType type = 2; }
main.cpp中:
#include <stdint.h> #include <stdio.h> #define __PROTOBUF_CPP_IMPL #ifdef __PROTOBUF_CPP_IMPL #include "person.pb.h" #else extern "C"{ #include "person.h" } #endif int main(int argc, char *argv[]) { static const uint32_t outputbuflen = 1024; uint8_t outputbuffer[outputbuflen]; uint32_t writtenlenght = 0; #ifdef __PROTOBUF_CPP_IMPL // C++ implementation. printf("Google C++ implementation;\n"); PhoneNumber number; number.set_number(0800123123.0); number.set_type(MOBILE); writtenlenght = number.ByteSize(); numberSerializeToArray(outputbuffer, writtenlenght); #else // Embedded c implementation. printf("embedded-c implementation:\n"); PhoneNumber number; number._number = 0800123123.0; number._type = _MOBILE; writtenlenght = PhoneNumber_write_delimited_to(&number, outputbuffer, 0); #endif for(uint32_t i = 0; i < writtenlenght; i++){ printf("%.2X ", outputbuffer[i]); } printf("\n"); return 0; }
真正的问题:
在Google protobuf C / Java库中应该使用哪些方法与嵌入式库成功通信?简单的答案可能是在所有消息中添加(解析时读取)前缀,但这会破坏代码.我应该寻找更好的嵌入式库吗?
更新:我尝试了这个名为nanopb的小型库,它现在很有用.
底线:protobuf-embedded-c与谷歌protobuf实现不兼容!
例如:
writtenlenght = PhoneNumber_write_delimited_to(& number,outputbuffer,-1);
或者你可以使用PhoneNumber_write(& number,outputbuffer,0);