您好我正在尝试使用protoc-c编译器实现proto3。这是.proto文件的包含。
syntax = "proto3";
message Submessage {
int32 value=1;
}
message DMessage {
Submessage a=1;
Submessage b=2;
/* Submessage c=3; */
}
序列化的C代码是:
#include <stdio.h>
#include <stdlib.h>
#include "example2.pb-c.h"
int main (int argc, const char * argv[])
{
DMessage msg = DMESSAGE__INIT; // DMESSAGE
Submessage sub1 = SUBMESSAGE__INIT; // SUBMESSAGE A
Submessage sub2 = SUBMESSAGE__INIT; // SUBMESSAGE B
/* Submessage sub3 = SUBMESSAGE__INIT; // SUBMESSAGE C */
void *buf;
unsigned len;
printf("1\n");
if (argc != 2 && argc != 3)
{ // Allow one or two integers
fprintf(stderr,"usage: dmessage a [b]\n");
return 1;
}
sub1.value = atoi (argv[1]);
msg.a = &sub1; // Point msg.a to sub1 data
// NOTE: has_b is not required like amessage, therefore check for NULL on deserialze
if (argc == 3) { sub2.value = atoi (argv[2]); msg.b = &sub2; } // Point msg.b to sub2 data
/* sub3.value = atoi(argv[3]);
msg.c = &sub3; */
len = dmessage__get_packed_size (&msg); // This is the calculated packing length
buf = malloc (len); // Allocate memory
dmessage__pack (&msg, buf); // Pack msg, including submessages
fprintf(stderr,"Writing %d serialized bytes\n",len); // See the length of message
fwrite (buf, len, 1, stdout); // Write to stdout to allow direct command line piping
free(buf); // Free the allocated serialized buffer
return 0;
}
反序列化的C代码是:
#include <stdio.h>
#include "example2.pb-c.h"
#define MAX_MSG_SIZE 4096
int main (int argc, const char * argv[])
{
DMessage *msg; // DMessage using submessages
Submessage *sub1,*sub2;// Submessages
char c; int i=0; // Data holders
uint8_t buf[MAX_MSG_SIZE]; // Input data container for bytes
while (fread(&c,1,1,stdin) != 0)
{
if (i >= MAX_MSG_SIZE)
{
fprintf(stderr,"message too long for allocated buffer\n");
return 1;
}
buf[i++] = c;
}
msg = dmessage__unpack(NULL,i,buf); // Deserialize the serialized input
if (msg == NULL)
{ // Something failed
fprintf(stderr,"error unpacking incoming message\n");
return 1;
}
sub1 = msg->a; sub2 = msg->b;
/* sub3 = msg->c; */
printf("Received: a=%d\n",sub1->value);
/* printf("Received: b=%d\n",sub2->value); */
if (msg->b != NULL) printf(" b=%d",sub2->value);
printf("\n");
dmessage__free_unpacked(msg,NULL);
return 0;
}
序列化代码工作正常,但问题是反序列化代码给出了“错误解包传入消息”。我尝试了各种组合,但它们没有用。有什么不对或我错过了什么? 任何人都可以帮助吗? 谢谢