read a binary to into a structure without packing in csharp

To read binary data into a structure in C#, you will need to use the BitConverter class and some pointer magic using the IntPtr type. Here's an example for reading a struct named "MyStruct" from a byte array:

main.cs
byte[] binaryData = ...; // your binary data
MyStruct myStruct;

// get the size of the struct
int structSize = System.Runtime.InteropServices.Marshal.SizeOf(typeof(MyStruct));

// make sure that the binary data is large enough to contain the struct
if (binaryData.Length < structSize)
{
    throw new ArgumentException("Binary data is too small to contain a MyStruct.");
}

// allocate a pointer to the buffer
IntPtr buffer = System.Runtime.InteropServices.Marshal.AllocHGlobal(structSize);

try
{
    // copy the binary data into the buffer
    System.Runtime.InteropServices.Marshal.Copy(binaryData, 0, buffer, structSize);

    // read the struct from the buffer
    myStruct = (MyStruct)System.Runtime.InteropServices.Marshal.PtrToStructure(buffer, typeof(MyStruct));
}
finally
{
    // free the allocated memory
    System.Runtime.InteropServices.Marshal.FreeHGlobal(buffer);
}
884 chars
29 lines

This code first gets the size of the struct using the Marshal.SizeOf method. It then makes sure that the binary data is at least as large as the struct, and allocates a buffer of that size using Marshal.AllocHGlobal. The binary data is then copied into the buffer using Marshal.Copy. Finally, the struct is read from the buffer using Marshal.PtrToStructure, and the allocated memory is freed using Marshal.FreeHGlobal.

Note that this method does not pack the struct, which means that the memory layout will be identical to the C/C++ equivalent of the struct.

gistlibby LogSnag