小编典典

AC#等效于C的读取文件I / O

c#

谁能告诉我如何在C#.NET版本2中直接将字节数组放入结构中?像fread在C语言中熟悉的一样,到目前为止,在读取字节流并自动填充结构方面并没有取得太大的成功。我已经看到了一些使用unsafe关键字在托管代码中存在指针轨迹的实现。

看一下这个样本:

public unsafe struct foobarStruct{

   /* fields here... */

   public foobarStruct(int nFakeArgs){
      /* Initialize the fields... */
   }

   public foobarStruct(byte[] data) : this(0) {
      unsafe {
         GCHandle hByteData = GCHandle.Alloc(data, GCHandleType.Pinned);
         IntPtr pByteData = hByteData.AddrOfPinnedObject();
         this = (foobarStruct)Marshal.PtrToStructure(pByteData, this.GetType());
         hByteData.Free();
      }
   }
}

我有两个构造函数的原因 foobarStruct

  • 是否不能有一个空的构造函数。
  • 实例化结构时,将一块内存(作为字节数组)传入构造函数。

该实施方案是否足够好,或者有更清洁的方法来实现这一目标?

编辑: 我不想使用ISerializable接口或其实现。我正在尝试读取一个二进制映像,以计算出使用的字段并使用PE结构确定其数据。


阅读 294

收藏
2020-05-19

共1个答案

小编典典

使用P /
Invoke编组器没有任何问题,这也不是不安全的,并且您不必使用unsafe关键字。弄错它只会产生错误的数据。与显式编写反序列化代码相比,使用起来容易得多,尤其是在文件包含字符串的情况下。您不能使用BinaryReader.ReadString(),它假定字符串是由BinaryWriter编写的。但是,请确保使用struct声明声明数据的结构,this.GetType()不太可能正常工作。

这是一个通用类,可用于任何结构声明:

  class StructureReader<T> where T : struct {
    private byte[] mBuffer;
    public StructureReader() {
      mBuffer = new byte[Marshal.SizeOf(typeof(T))];
    }
    public T Read(System.IO.FileStream fs) {
      int bytes = fs.Read(mBuffer, 0, mBuffer.Length);
      if (bytes == 0) throw new InvalidOperationException("End-of-file reached");
      if (bytes != mBuffer.Length) throw new ArgumentException("File contains bad data");
      T retval;
      GCHandle hdl = GCHandle.Alloc(mBuffer, GCHandleType.Pinned);
      try {
        retval = (T)Marshal.PtrToStructure(hdl.AddrOfPinnedObject(), typeof(T));
      }
      finally {
        hdl.Free();
      }
      return retval;
    }

文件中数据结构的示例声明:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
struct Sample {
  [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 42)]
  public string someString;
}

您需要调整结构声明和属性,以与文件中的数据匹配。读取文件的示例代码:

  var data = new List<Sample>();
  var reader = new StructureReader<Sample>();
  using (var stream = new FileStream(@"c:\temp\test.bin", FileMode.Open, FileAccess.Read)) {
    while(stream.Position < stream.Length) {
      data.Add(reader.Read(stream));
    }
  }
2020-05-19