It seems easy but I can't see it easy at all. My question is I have a struct and I need to convert it to byte stream without any additional bytes for types nor padding nor metadata. Assume I have a struct
[StructLayout(LayoutKind.Sequential)]
public struct MyStruct
{
public ushort a;
public uint b;
public uint c;
public ushort d;
}
Remark: I can't change the pack here to 1(Project constrains), so using the following solution won't work as there's a padding added
int size = Marshal.SizeOf(typeof(T));
byte[] arr = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(str, ptr, true);
Marshal.Copy(ptr, arr, 0, size);
Marshal.FreeHGlobal(ptr);
Also Remark: I can't use Binary format serialization as there's a metadata added. All what I want simply if a=1 b=2 c=3 d=4 to get binary format in a GENERIC WAY as
arr {byte[12]} byte[]
[0] 1 byte
[1] 0 byte
[2] 2 byte
[3] 0 byte
[4] 0 byte
[5] 0 byte
[6] 3 byte
[7] 0 byte
[8] 0 byte
[9] 0 byte
[10] 4 byte
[11] 0 byte
Any help?
BitConverter?GetFields) it would be very generic.