gpt4 book ai didi

c - 在 C 中序列化一个简单的结构

转载 作者:太空宇宙 更新时间:2023-11-03 23:51:06 25 4
gpt4 key购买 nike

我正在完成客户端/服务器程序,其中客户端使用堆栈执行二进制代码。客户端必须能够连接到服务器,然后服务器将继续执行堆栈。为此,我需要将堆栈结构发送到服务器。所以我需要先序列化我的“堆栈”对象,然后反序列化它,但我不擅长关闭指针操作。我一直在寻找一个库,但来自 google 的 JSON 和 Prot-c 看起来又重又复杂,所以如果我能得到一些帮助来手动序列化/反序列化该堆栈,那将非常方便。

我的堆栈基于列表实现:

struct list {
int Element;
list next;
};

struct stack
{
list l;
};

将现有“堆栈”对象发送到我的服务器的最简单方法是什么?

谢谢!

最佳答案

基于库:

BSON代替 JSON,它比 Google Protocol Buffer 更轻,但仍然有点笨重。

可以找到更便宜的替代品 here .

自己的实现:

next 字段的类型应该是 list* 而不是 list。否则你有一个循环定义,一个列表不能合理地包含整个其他列表。

另外,根据个人喜好,我将内部列表节点数据类型称为 node 并将列表的顶端(第一个节点)称为 list >.

您还需要 typedef struct list list 以便在其他结构定义中使用 listlist*

例子:

/* this is your list.h file */

/* Forward declaration of `node` allows us to use
* `node` as a datatype in stead of using `struct node`
* everywhere.
*/
typedef struct node node;

/* Creating an alias called `list` for `node` types
* we will only use this when refferring to the first
* node of the list.
*/
typedef node list;

/* A container that will help us carry around multiple
* types of data.
*/
typedef struct any_value any_value;

/* An enum that will be used by the any_value container
* to discern what type of data is currently present.
*/
typedef enum type_flag type_flag;

/* this is your list.c file */

struct node {
/* A void pointer to the value allows us to use
* different types of values.
*/
any_value value;
node* next;
node* prev;
}

enum type_flag {
INTEGER, STRING, SUBLIST
}

struct any_value {
type_flag type;
int length;
void* value;
}

关于c - 在 C 中序列化一个简单的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19683864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com