C#读取二进制文件到struct(带子结构)

时间:2014-08-19 16:22:37

标签: c# struct binary

我来自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?

2 个答案:

答案 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;
}

答案 1 :(得分:0)

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

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} ;

}