英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论