Can anyone tell me how to get a array of bytes into a structure in a direct fashion in C# .NET version 2? Like the familiar fread
as found in C, so far I have not had much success in reading a stream of bytes and automatically filling a structure. I have seen some implementations where there is pointer hocus-pocus in the managed code by using the unsafe
keyword.
Have a look at this sample:
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();
}
}
}
The reason I have two constructors in foobarStruct
- Is there cannot be an empty constructor.
- Pass in a block of memory (as a byte array) into the constructor when instantiating the structure.
Is that implementation good enough or is there a much cleaner way to achieve this?
Edit: I do not want to use the ISerializable interface or its implementation. I am trying to read a binary image to work out the fields used and determine its data using the PE structures.
fread
into astruct
due to padding and alignment considerations – Malo