user1488464
user1488464

Reputation: 61

Byte Array "Union" overlay in c# StructLayout.Explicit

I want to have a kind of c-style uion whithin a c# struct type.

For some reason i get an exception everytime I allocate a type that i defined. Here is my own type. The basic idea is that i have access to the "pointer" of this struct. Unfortunately i get an Exception TypeLoadException:

Additional information: Could not load type 'ManagedTarget.FngPeriodeParameterType' from assembly 'ManagedTarget, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because it contains an object field at offset 0 that is incorrectly aligned or overlapped by a non-object field.

What is wrong?

[StructLayout(LayoutKind.Explicit, Size = 16)]
unsafe internal struct FngPeriodeParameterType
{
  [FieldOffset(0)]
  public Byte[] ByteArray;

  [FieldOffset(0)]
  public UInt32 Repetitions;

  [FieldOffset(4)]
  public Int16 Amplitude;

  [FieldOffset(6)]
  public Int16 Offset;

  [FieldOffset(8)]
  public Int16 Gain;

  [FieldOffset(10)]
  public UInt16 Selection;

  [FieldOffset(12)]
  public UInt32 Step;
}

Upvotes: 5

Views: 2789

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062755

If your intent is that ByteArray is the raw data, it must be a fixed buffer; at the moment, it is simply a reference to an unrelated byte[] on the heap - and you can't overlap a reference and a uint:

[FieldOffset(0)]
public fixed byte ByteArray[16];

Working with it can be a pain, though; I usually add helper methods like:

public void ReadBytes(byte[] data)
{
    fixed (byte* ptr = ByteArray)
    {
        for (int i = 0; i < 16; i++)
            data[i] = ptr[i];
    }
}

Upvotes: 6

Related Questions