protobuf c语言使用样例
时间: 2024-01-05 13:21:15 浏览: 140
以下是使用Protobuf在C语言中进行序列化和反序列化的示例:
1. 序列化示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include "amessage.pb-c.h"
int main() {
AMessage message = AMESSAGE__INIT;
void *buf;
unsigned len;
// 设置消息字段的值
message.id = 1; message.name = "John Doe";
message.email = "johndoe@example.com";
// 序列化消息
len = amessage__get_packed_size(&message);
buf = malloc(len);
amessage__pack(&message, buf);
// 打印序列化后的数据
for (unsigned i = 0; i < len; i++) {
printf("%02x ", ((uint8_t *)buf)[i]);
}
printf("\n");
// 释放内存
free(buf);
return 0;
}
```
2. 反序列化示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include "amessage.pb-c.h"
int main() {
AMessage *message;
void *buf;
unsigned len;
// 假设这是从网络或文件中接收到的序列化数据
uint8_t serialized_data[] = {0x08, 0x01, 0x12, 0x08, 0x4a, 0x6f, 0x68, 0x6e, 0x20, 0x44, 0x6f, 0x65, 0x1a, 0x12, 0x6a, 0x6f, 0x68, 0x6e, 0x64, 0x6f, 0x65, 0x40, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x63, 0x6f, 0x6d};
// 反序列化消息
len = sizeof(serialized_data);
buf = malloc(len);
memcpy(buf, serialized_data, len);
message = amessage__unpack(NULL, len, buf);
// 打印消息字段的值
printf("ID: %d\n", message->id);
printf("Name: %s\n", message->name);
printf("Email: %s\n", message->email);
// 释放内存
amessage__free_unpacked(message, NULL);
free(buf);
return 0;
}
```
阅读全文