title: Marshal struct with dynamic size array
body: <p>I am having trouble marshalling a struct with a dynamic size array. The fixed length arrays are simple; just add </p>
  
  <pre><code>[MarshalAs(UnmanagedType.ByValArray, SizeConst = TheSizeOfTheArray)]
  </code></pre>
  
  <p>However, I'm at a loss when it comes to dynamic size arrays. For simplicity, I will omit everything that's not relevant in my code.</p>
  
  <p>The device I am sending this serialized struct to expects an ushort to inform about the length of the array, followed by the array itself, and a CRC at the end.</p>
  
  <pre><code>[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
  public struct MyNetworkMessage
  {
      public ushort Length { get; }
  
      // This attribute does not work as I had hoped
      [MarshalAs(UnmanagedType.ByValArray, SizeParamIndex = 1)]
      private byte[] _messageData;
  
      public ushort Crc { get; private set; }
  
      public byte[] MessageData
      {
          get { return _data; }
          private set { _data = value; }
      }
  
      public MyNetworkMessage(byte[] data)
      {
          MessageData = data;
          Length = (ushort)data.Length;
          Crc = Helper.CalcCrc(MessageData);
      }
  }
  </code></pre>
  
  <p>This struct needs to be serialized to a byte array which is sent over the wire to another device, where the first two bytes is the length of the array, and the last two bytes is the CRC of the MessageData:</p>
  
  <pre><code>Byte 0..1       Length of Data-field, N
  Byte 2..N+2     Data
  Byte N+3..N+4   CRC
  </code></pre>
  
  <p>I have many different structs like this that need to be serialized and sent over the wire as byte arrays, so a generic way of handling this is what I am after. Creating a correct byte array for this one example is simple enough, but I don't want to have to write serialization/deserialization for each and every struct, when they all only contain simple data.</p>
  
  <p>I have seen similar questions asked earlier here, marked as duplicates, without seeing any satisfactory answers.</p>