二进制格式反序列化

huangapple go评论63阅读模式
英文:

Binary Format Deserialization

问题

在C#程序中,我正在使用BinaryFormatter().Serialize()方法对数据模型进行序列化,然后通过TCP套接字将序列化的二进制流发送到C程序。现在,在C程序中,我想提取数据,以了解BinaryFormatter().Serialize()生成字节流的格式。我想在C中编写一个反序列化函数,用于重新生成由C#中的BinaryFormatter().Serialize()序列化的数据。是否有关于此的文档或信息可供参考?

英文:

I have two programs one is written in C and another is in C#. In the C# program, I am using BinaryFormatter().Serialize() method to serialize a data model and then send the serialized binary stream to C program through a TCP socket. Now In the C program, I want to extract the data so that I want to know the format of how BinaryFormatter().Serialize() generates the byte stream. I want to write a deserializer function in C for regenerating data serialized by BinaryFormatter().Serialize() in C#. Is there any documentation or information available for this?

答案1

得分: 6

从BinaryFormatter在C中反序列化数据的唯一方法是调用.NET框架并使用BinaryFormatter。

但这真的不是通过网络传输数据的最佳方式。BinaryFormatter速度慢、不安全且脆弱。格式甚至可能在两个.NET版本之间发生变化。

一个更好的方法是使用专为不同系统间通信设计的序列化格式。我使用过Protobuf.NET并取得了良好的效果,C应该也有一些Protobuf的实现。BSON、像JSON/XML这样的文本格式也可能是替代方案。

如果你正在编写一个"性能密集型"应用程序,最好在选择库之前查看一些基准测试,或进行自己的性能测试。在我看过的基准测试中,BinaryFormatter通常是最慢的选择,因此如果你关心性能,它不是一个好选择。我唯一会使用它的原因是从某个旧系统中读取数据。

英文:

The only way to deserialize data from BinaryFormatter in C would be to invoke the .net framework and use BinaryFormatter.

But this is really not the best way to transfer data over the network. BinaryFormatter is slow, insecure, and fragile. The format might even change between two .net versions.

A much better way would be to use a serialization format intended for communication between different systems. I have used Protobuf .net with good result, and C should have some protobuf implementation. BSON, textbased formats like json/xml might also be alternatives.

If you are writing a "performance intensive" application it is probably a good idea to take a look at a few benchmarks before choosing a library, or do your own performance testing. In the benchmarks I have seen, BinaryFormatter is often the slowest alternative, so it is not a good choice if you are concerned about performance. The only reason I would ever use it is for reading data from some legacy system.

huangapple
  • 本文由 发表于 2023年5月11日 18:34:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76226684.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定