c#将二进制文件读取为结构体(带有子结构体)

本文关键字:结构体 二进制文件 读取 | 更新日期: 2023-09-27 18:18:53

我来自C/c++,所以在C/c++中构造二进制只是简单地转换一个指向原始二进制的指针。但是,如果我有这样的东西呢:

struct STRUCT {
  SUBSTRUCT a;
  ushort    b[3];
  int       c;
}
struct SUBSTRUCT {
  ushort   d[3];
}

的二进制文件格式为

AA AA AA AA AA AA BB BB BB BB BB BB CC CC CC CC

如何将此二进制文件转换为c#中的STRUCT ?

c#将二进制文件读取为结构体(带有子结构体)

这可能是最简单和最直接的方法。您需要自己处理任何字节顺序问题:

class Struct
{
  public static Struct Rehydrate( BinaryReader reader )
  {
    Struct instance = new Struct() ;
    instance.a = SubStruct.Rehydrate( reader ) ;
    for ( int i = 0 ; i < instance.b.Length ; ++i )
    {
      instance.b[i] = reader.ReadUInt16() ;
    }
    instance.c = reader.ReadInt32() ;
    return instance ;
  }
  public void Dehydrate( BinaryWriter writer )
  {
    this.a.Dehydrate( writer ) ;
    foreach( ushort value in this.b )
    {
      writer.Write( value ) ;
    }
    writer.Write( this.c ) ;
    return ;
  }
  public SubStruct a = null ;
  public ushort[]  b = {0,0,0};
  public int       c = 0 ;
}
class SubStruct
{
  public static SubStruct Rehydrate( BinaryReader reader )
  {
    SubStruct instance = new SubStruct() ;
    for ( int i = 0 ; i < instance.d.Length ; ++i )
    {
      instance.d[i] = reader.ReadUInt16() ;
    }
    return instance ;
  }
  public void Dehydrate( BinaryWriter writer )
  {
    foreach( ushort value in this.d )
    {
      writer.Write(value) ;
    }
    return ;
  }
  public ushort[] d = {0,0,0} ;
}

您可以打开该文件并使用BinaryReader读取它,然后使用Marshal将其强制转换为Struct。这不是一个明确的答案,但应该会给你指明正确的方向。

public static T ByteToType<T>(BinaryReader reader)
{
    byte[] bytes = reader.ReadBytes(Marshal.SizeOf(typeof(T)));
    GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
    T theStructure = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
    handle.Free();
    return theStructure;
}