Home » c# » Struct union in C#, get exception when new the struct

Struct union in C#, get exception when new the struct

Posted by: admin February 21, 2020 Leave a comment

Questions:

My question is to new a union-struct, but get exception (about incorrect alignment) while running. Is there something wrong with my partial code? Any better method to solve without using “unsafe”?

enter code here

public struct SR_CONFIG
{
   public UInt32    dwRate;
   public int       bVAD;
   public UInt16    wSilenceStart;
   public UInt16    wSilenceEnd;
   public UInt16    wMaxLength;
}

[StructLayout(LayoutKind.Explicit)]
public struct CmdStruct_Union
{
   [FieldOffset(0)] public SR_CONFIG    SrParams;

   [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
   [FieldOffset(0)] public Byte[] rev;
}

CmdStruct_Union myStruct = new CmdStruct_Union(); // <----- get exception when running
How to&Answers:

If you can enable unsafe code in the project, then this solution works:

[StructLayout(LayoutKind.Explicit)]
public unsafe struct CmdStruct_Union
{
    [FieldOffset(0)] public SR_CONFIG SrParams;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
    [FieldOffset(0)] public fixed byte rev[16];
}

Accessing to the rev items is same as in regular arrays in C# (but method must be also marked as “unsafe”, like struct above). Remember that debugger will show you only the first element of fixed array.

More about fixed size buffers: https://docs.microsoft.com/en-US/dotnet/csharp/programming-guide/unsafe-code-pointers/fixed-size-buffers