任何人都可以告诉我如何在C#.NET版本2中以直接方式将一个字节数组添加到结构中?就像fread在C中发现的熟悉一样,到目前为止,我在读取字节流并自动填充结构方面没有取得多大成功.我已经看到了一些实现,其中通过使用unsafe关键字在托管代码中存在指针hocus-pocus .
看看这个样本:
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我有两个构造函数的原因 foobarStruct
这种实现是否足够好还是有更清洁的方法来实现这一目标?
编辑:我不想使用ISerializable接口或其实现.我正在尝试读取二进制图像以计算出使用的字段并使用PE结构确定其数据.