以二进制打包格式序列化结构 [英] Serialize Struct in Binary, Packed Format

查看:64
本文介绍了以二进制打包格式序列化结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#中是否有一种方法可以将结构序列化为二进制流(MemoryStream),以使二进制表示形式等效于该结构的视觉布局(即无填充)?

Is there a way in C# to serialize a struct to a binary stream (MemoryStream) such that the binary representation is equivalent to how the struct is visually layed out (i.e. no padding)?

在C/C ++中,使用#pragma命令告诉编译器压缩结构的内容,以使字段之间没有填充.如果您有两个应用通过套接字来回传递消息,这将很有帮助.禁用打包后,您可以简单地在套接字上发送"该结构的内容,而不必担心将每个字段分别打包到二进制缓冲区中(必要时还必须进行字节序交换).

In C/C++, you use #pragma commands to tell the compiler to pack the struct's so that there is no padding between the fields. This is helpful if you have two apps passing messages back and forth via sockets. With packing disabled, you can simply "send" the contents of the struct over the socket and not have to worry about packing each field individually into a binary buffer (also have to do endianness swapping if necessary).

推荐答案

不,除非您使用不安全的代码.使用协议缓冲区或节俭或类似的东西;根据我的经验,我不建议.NET内置二进制序列化.您还可以使用 BinaryWriter/BinaryReader 进行序列化/反序列化(使用反射或预先生成的序列化代码).至于打包,您可以使用 [StructLayout] 属性对其进行控制.

Not unless you use unsafe code. Use Protocol Buffers or Thrift or something like that; I wouldn't recommend .NET built-in binary serialization based on my experience. You could also serialize/deserialize with BinaryWriter/BinaryReader (use reflection or pre-generate serialization code). As for packing, you can control it with the [StructLayout] attribute.

这篇关于以二进制打包格式序列化结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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