问题描述
我想从二进制读取结构。
在C ++中,我会做这样的:
I want to read structures from binary.In C++ I would do it like this:
stream.read((char*)&someStruct, sizeof(someStruct));
有没有在C#中以类似的方式?该BinaryReader仅适用于内置类型。在.NET 4中有一个MemoryMappedViewAccessor。它提供了像方法读取< T>
这似乎是我想要的,但我必须手动跟踪该文件中我想读。
有没有更好的办法?
Is there a similar way in C#? The BinaryReader only works for built-in types. In .NET 4 there is a MemoryMappedViewAccessor. It provides methods like Read<T>
which seems to be what I want, except that I manually have to keep track of where in the file I want to read.Is there a better way?
推荐答案
这是可以做到在C#中类似的东西,但你必须让你控制它究竟是如何布局中有很多属性适用于结构记忆。默认JIT编译器的控制结构成员如何在存储器中,这通常意味着它们被重新安排并填充为最有效的布局考虑速度和内存使用布置
It's possible to do something similar in C#, but then you would have to apply a lot of attributes to a structure so that you control exactly how it's laid out in memory. By default the JIT compiler controls how structure members are laid out in memory, which usually means that they are rearranged and padded for the most efficient layout considering speed and memory usage.
最简单的方法,通常是使用BinaryReader读取该文件的结构的单独构件,并把该值在属性中的一类,即,将数据手动deserialise成类实例
The simplest way is usually to use the BinaryReader to read the separate members of the structure in the file, and put the values in properties in a class, i.e. manually deserialise the data into a class instance.
通常它的读取是在该操作的瓶子颈部的文件,所以读取分开的构件不会明显影响性能的小的开销。
Normally it's reading the file that is the bottle neck in this operation, so the small overhead of reading the separate members doesn't affect the performance noticeably.
这篇关于C#中,读取二进制文件结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!