protobuf的C简单的代码例子(二)

本文介绍了一个简单的CMessage结构体的序列化与反序列化过程,使用protobuf-c库进行数据打包和解包操作。文章通过具体代码展示了如何将一系列整数序列化为字节流,并在另一端将这些字节流反序列化回原始数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建一个cmessage.proto 文件:

message CMessage
{
    repeated int32 c=1;
}

源代码生成的方法请参考  《protobuf的C简单的代码例子(一)》

下面给出打包代码:

#include<stdio.h>
#include<stdlib.h>
#include"cmessage.pb-c.h"

int main (int argc,constchar* argv[])
{
    CMessage msg = CMESSAGE__INIT;  // CMessage(repeated int32)
    void*buf;                     // Buffer to storeserialized data
    unsigned len,i;                // Length of serialized data
    msg.n_c = argc -1;                     // Save number ofrepeated int32
    msg.c = malloc (sizeof(int)* msg.n_c);// Allocate memoryto store int32
    for(i =0; i < msg.n_c; i++)
        msg.c[i]= atoi (argv[i+1]);        // Access msg.c[] as array
    len =cmessage__get_packed_size (&msg);  // This iscalculated packing length
    buf = malloc (len);                     // Allocaterequired serialized buffer length
    cmessage__pack (&msg, buf);             // Pack the data

    fprintf(stderr,"Writing %dserialized bytes\n",len);// See the lengthof message
    fwrite (buf, len,1, stdout);           // Write to stdout to allow direct command line piping

    free (msg.c);// Free storage forrepeated int32            
    free (buf);   // Free serializedbuffer
    return0;
}

注意

  • 使用 C_MESSAGE__INIT宏创建信息架构
  • the n_XXX member is generated for a repeated field XXX.
  • n_XXX 成员是通过复域XXX(可简单理解为类似数组的结构)产生的。

下面给出解包的代码

#include<stdio.h>
#include"cmessage.pb-c.h"
#define MAX_MSG_SIZE  4096

int main (int argc,constchar* argv[])
{
    CMessage*msg;
    uint8_t buf[MAX_MSG_SIZE];
    size_t msg_len = read_buffer (MAX_MSG_SIZE, buf);

    msg = cmessage__unpack (NULL, len, buf);// Deserialize theserialized input
    if(msg == NULL)
    {// Something failed
        fprintf(stderr,"errorunpacking incoming message\n");
        return1;
    }
   
    for(i =0; i < msg->n_c; i++)
    {// Iterate through all repeated int32
        if(i >0)
            printf (", ");
        printf ("%d", msg->c[i]);
    }
    printf ("\n");
   
    cmessage__free_unpacked(msg,NULL);// Free the messagefrom unpack()
    return0;
}


$ ./cmessage_serialize 12 3 4|./ cmessage_deserialize   --->管道命令
Writing:6 serialized bytes   ---->打印信息
12,3,4   ---->打印信息

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值