如何在C中序列化数据 [英] How to serialize data in C

查看:46
本文介绍了如何在C中序列化数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 c 编写一个服务器-客户端应用程序,需要来回发送一些结构.

I am writing a server-client application in c and need to send some structures back and forth.

如何以独立于平台的方式序列化数据?

How can I go about serializing the data in a platform independent manner?

推荐答案

如果您需要担心不同版本的服务器和客户端之间的兼容性,我会使用 Google 协议缓冲区或 JSON(无论是现有的实现,还是编写你自己).如果版本始终保持同步,只需编写您自己的二进制序列化,或者甚至将内存结构定制为序列化"形式并使用访问函数来读取和写入它.这基本上需要将数字以固定字节序存储为固定数量的字节,或者如果您想花哨的话,可以使用某种 vlc 格式,并使用某种类型的对象句柄(最简单的是数组的偏移量)代替显式指针当一个对象需要引用另一个对象时.

If you need to worry about compatibility between different versions of the server and client, I'd use Google protocol buffers or JSON (either an existing implementation, or write your own). If the versions will always be in sync, just write your own binary serialization, or even tailor the in-memory structure to be a 'serialized' form and use access functions to read and write it. This basically entails storing numbers as a fixed number of bytes in a fixed-endian order, or some vlc format if you want to get fancy, and using object handles of some sort (simplest is an offset into an array) in place of explicit pointers when one object needs to refer to another.

在内部以序列化"形式保存数据的一个非常好的附带好处是,您可以在磁盘上处理大量数据集(例如通过 mmap),而无需编写自己的复杂缓存代码.

One really nice side benefit of keeping data in a 'serialized' form internally is that you can work with huge data sets on disk (for example via mmap) without having to write your own complex caching code.

这篇关于如何在C中序列化数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆