【发布时间】:2015-02-20 07:56:43
【问题描述】:
为我的 C 语言代码试用 Google 协议缓冲区。
messagefile.proto
===================
mesage othermessage
{
optional string otherstring = 1;
}
message onemessage
{
optional string messagestring = 1;
optional int32 aninteger = 2;
optional othermessage otr_message= 3;
}
===============================================
--> protoc-c messagefile.proto --c_out=./ 这导致了两个文件
--> messagefile.pb-c.c 和 messagefile.pb-c.h
现在我的代码文件将尝试使用 简单示例.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "messagefile.pb-c.h"
#include <stdbool.h>
int main(int argc, const char * argv[])
{
onemessage msg = ONE__MESSAGE__INIT; //from generated .h code file
void *buf;
unsigned int len;
char *ptr;
//integer initialization
msg.has_aninteger = true;
msg.aninteger = 1;
//accessing the string in onemessage
msg.messagestring = malloc(sizeof("a simple string"));
strncpy(msg.messagestring,"a simple string",strlen("a simple string"));
//trying to initialize the string in the nested structure othermessage
msg.otr_message = malloc(sizeof(othermessage));
msg.otr_message->otherstring = malloc(sizeof("a not so simple string"));
strncpy(msg.otr_message->otherstring,"a not so simple string",strlen("a not so simple string"));
//lets find the length of the packed structure
len = one_message__get_packed_size(&msg); //from generated .h code
//lets arrange for as much size as len
buf = malloc(len);
//lets get the serialized structure in buf
one_message__pack_to_buffer(&msg,buf); //from generated code
//write it to a stream, for now the screen
fwrite(buf,len,1,stdout);
//free buffer
free(buf);
return 0;
}
我将它编译为 gcc -o testout messagefile.pb-c.c simpleexample.c -lprotobuf-c
我面临的问题是在尝试初始化嵌套的 othermessage 变量然后调用 get_packed_size 时会引发分段错误。
我尝试了各种组合,我可以说,每当嵌套类中有字符串时,我都面临着使用 google protoc 访问那些字符串的问题。 我错过了什么吗?有什么问题吗。
谁能帮忙。
注意:可能存在一些一般语法错误,请忽略它们。
谢谢。
【问题讨论】:
标签: c serialization deserialization protocols protocol-buffers