8

我在一个小型系统上使用protobuf-embedded-c将不同的数据从它传输到 PC。问题是,如果我在两端使用嵌入式库,一切正常。如果我在 PC 上使用 google C++,它就不再工作了。我想我将问题追溯到每条消息中都有长度前缀的嵌入式库,但我似乎无法在 C++ 库上以一种好的方式做到这一点。这是我用来调试的测试应用程序:

人.proto:

enum PhoneType {
  MOBILE = 0;
  HOME = 1;
  WORK = 2;
}

message PhoneNumber {
  required float number = 1;
  required PhoneType type = 2;
}

主.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 与 google protobuf 实现不兼容!

Protobuf 比较。

4

2 回答 2

2

将偏移量设为 -1 而不是 0。例如:

writtenlenght = PhoneNumber_write_delimited_to(&number, outputbuffer, -1);

或者你可以使用PhoneNumber_write(&number, outputbuffer, 0);

于 2012-06-27T10:49:17.460 回答
0

In protobuf-embedded-c's generated C file, there exists

int $name$_read(void *_buffer, $if(empty)$$else$struct $name$ *_$name$, $endif$int offset, int limit);
int $name$_write($if(empty)$$else$struct $name$ *_$name$, $endif$void *_buffer, int offset);

which appear to do the expected, reading/writing a message without a size prefix. I don't know why these aren't exposed in the generated H file, but you should be able to add it yourself.

于 2012-06-03T20:00:38.110 回答