我是 protobuf 的新手
当我通过 recv 端的套接字通信发送 protobuf 变量时,我试图显示 protobuf 的字符串变量,我在这个剩余的数据类型中得到了分段,而不是字符串,它们工作正常,但字符串变量的情况下我得到分段我怎么能过来在 Protobuf 字符串数据类型分段错误中,除了我们有任何其他数据类型用于存储字符串数据类型。
我用字符串变量名创建了一个 proto_socket.proto 我正在用 protoc compiler() 编译 proto_socket.proto它创建两个文件protoc proto_socket.proto --c_out <path>
两个文件proto_socket.pb-c.h
。proto_socket.pb-c.c
通过使用这些文件,我创建了一个proto_server.c
和proto_client.c
. 并编译它。但是在两个程序运行时,我在 recv 端发送了一个 protobuf 变量,由于试图显示字符串变量,它给出了分段错误。
proto_socket.proto
syntax="proto2";
message messages{
optional int32 age=1;
optional int32 year=2;
optional string name=3;
}
为 .proto 生成的结构
struct _Messages
{
ProtobufCMessage base;
protobuf_c_boolean has_age;
int32_t age;
protobuf_c_boolean has_year;
int32_t year;
char *name;
};
proto_client.c
void *clientThread(void *arg)
{
Messages t_message;
//while(1)
{
int32_t s32_send_status;
t_message.age =70;
t_message.year=2018;
t_message.name="anu";
s32_send_status=send(gs32_clientSocket ,(unsigned char *)
(&t_message),sizeof(t_message) ,0);
if(s32_send_status>0){
printf("data send to server.\n");
}
else{
printf("failed to send data to server\n");
}
/*gs32_valread=read( gs32_clientSocket , gars32_buffer , 1024);
if(gs32_valread==0){
printf("connection loss\n");
exit(1);
}
else if(gs32_valread<0){
printf("error:read\n");
exit(1);
}
else{
printf("server replay:%s\n",gars32_buffer);
}*/
}
sleep(2);
return NULL;
}
proto_server.c
void *socketThread(void *arg)
{
Messages t_message;
//while(1)
{
gs32_valread = read( gs32_new_socket,(unsigned char *)
(&t_message), 1024);
if(gs32_valread==0){
printf("disconnected\n");
exit(1);
}
else if(gs32_valread<0){
printf("error\n");
exit(1);
}
else{
printf("age=%d\n",t_message.age );
printf("year=%d\n",t_message.year);
gs32_birth_year=(t_message.year)-(t_message.age);
printf("birth year=%d\n",gs32_birth_year);
printf("name=%s\n",t_message.name);
}
sleep(1);
close(gs32_new_socket);
}
return NULL;
}
结果,
age=70
year=2018
birth year=1948
Segmentation fault (core dumped)