0

我目前正在尝试使用 nanopb 序列化字符串并在 python/java 中解码消息。我没有麻烦的整数,我可以序列化和反序列化。但是当涉及到字符串时,我不断收到同样的错误:'utf-8' codec can't decode byte 0xff in position 2: 'utf-8' codec can't decode byte 0xff in position 2: invalid start byte in场地:

我认为这可能是 Python 解码问题,所以我修改 with open('FileSerialized.bin', 'rb') as f:

with open('FileSerialized.bin', encode='utf-8') as f:

我尝试使用 Java 中的解析器,但它给出了同样的错误。因此,我认为问题在于我在 C 中编码消息的方式。我正在执行以下操作:

在 nanopb 提供了 .proto 的转换之后:

typedef struct _ProtoExample {
    int32_t Value1;  //this is deserialized correctly
    char Value2[6]; //here is where I have trouble
}

我尝试通过执行以下操作来填充 char 数组:

pb_ostream_t stream = pb_ostream_from_buffer( buffer, BUFFER_SIZE );
ProtoExample Message;
Message.Value1= S_generalConfig_s.EntityType;
Message.Value2[0] = 'a';

pb_encode( &stream, ProtoExample _fields, &Message);

尝试解码后,我在尝试读取 Value2 时发现错误。

4

1 回答 1

1
ProtoExample Message;
Message.Value1= S_generalConfig_s.EntityType;
Message.Value2[0] = 'a';

初始化消息结构是个好主意。否则,如果您忘记初始化某些字段,它将包含随机数据。所以将第一行更改为:

ProtoExample Message = ProtoExample_init_default;

ProtoExample_init_default是 nanopb 生成的初始化宏,它将包含 .proto 文件中定义的任何默认值。您也可以使用ProtoExample_init_zero来初始化为空值。

实际问题是您的字符串未终止。在 C 中,字符串必须以 '\0' 字符结尾才有效。所以你需要添加:

Message.Value2[1] = '\0';

在您的单个字符之后设置终止符。如果添加默认初始化,它将所有字节设置为零。在这种情况下,这有点多余,但确保字符串终止通常是一种很好的编程习惯。

于 2019-10-23T16:08:27.347 回答