0

How to convert structures to a byte array in C#?

I have 2 structures below:

    public struct HeaderCommand
    {
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = SIZE_HEADER_COMMAND)] public byte[] byteSize;
        public HeaderCommandStruct val;

    }

    public struct HeaderCommandStruct
    {
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)] public char[] robotName;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)] public char[] robotVersion;
        public byte stepInfo;
        public byte sof;
        public int invokeId;
        public int dataSize;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)] public char[] reserved;
        public int cmdId;
    }

I'd like to convert HeaderCommand Structure to byte array using StructureToByte Method below.

    public static byte[] StructureToByte(HeaderCommand data)
    {
        int dataSize = Marshal.SizeOf(data);
        byte[] arr = new byte[dataSize];

        IntPtr ptr = Marshal.AllocHGlobal(dataSize);
        Marshal.StructureToPtr(data, ptr, false);
        Marshal.Copy(ptr, arr, 0, dataSize);
        Marshal.FreeHGlobal(ptr);
        return arr;
    }

When I run the code, an exception "System.ArgumentException" is thrown. I guess the problem is the size of byte array is different from Headercommand structure.

the Exception occurs at the line 'Marshal.StrucutureToPtr(data,ptr,false)'

Am I missing something or is it wrong to check the structure size by using Marshal.Sizeof(struct)?

  • 1
    When posting about an exception you should include the exact line it occurred on and the message. – juharr Apr 20 '18 at 11:27
  • Honestly never tried this with complex or nested structs... but I do know all my structs have `[StructLayout(LayoutKind.Sequential, Pack = 1)]` on them. – Nyerguds Apr 20 '18 at 11:31
  • I am not sure if I am missing something here but it seems the code posted is identical to the duplicate code. The code compiles & runs OK for me unless SIZE_HEADER_COMMAND is set to 0 - then I get a System.ArgumentException. Note that struct alignment is on integers (4 bytes). https://dotnetfiddle.net/I4hT0y – PaulF Apr 20 '18 at 12:01

0 Answers0