C# StructLayout/FieldOffset and indexing in arrays

后端 未结 2 725
借酒劲吻你
借酒劲吻你 2020-12-11 18:33

I\'m having a bit of a problem using FieldOffset correctly with arrays. The code below is an example where it doesn\'t work correctly for me:

[StructLayout(L         


        
2条回答
  •  孤城傲影
    2020-12-11 19:37

    Your FieldOffset defines where each of your data elements are inside the struct..

    By setting them all to 0, you're telling the compiler that they all at position 0.

    The second thing I see is you're creating an array of bytes, shorts, and ints.

    see: MSDN StructLayoutAttribute

    [StructLayout(LayoutKind.Explicit)]
    public struct IndexStruct {
            [FieldOffset(0)]
            public byte[16] data;
    
            [FieldOffset(16)]
            public short idx16;
    
            [FieldOffset(18)]
            public int idx32;
    }
    

提交回复
热议问题