C# StructLayout/FieldOffset and indexing in arrays

后端 未结 2 724
借酒劲吻你
借酒劲吻你 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:17

    The problem is (from what I can see) that you've unioned the references of the arrays - so whichever array gets set last will win. Once there is an array, it is using the indexer (not byte offset) - so the size doesn't matter.

    The way to do this "properly" (or improperly, as the case may be) would probably be with unsafe code - taking the pointer to the array - something like:

        IndexStruct s = new IndexStruct();
        s.data = new byte[] { 1, 0, 0, 0, 1, 1 };
    
        unsafe
        {
            fixed (short* data = s.idx16)
            {
                Console.WriteLine(data[0]); // should be 1 (little-endian)
                Console.WriteLine(data[1]); // should be 0
                Console.WriteLine(data[2]); // should be 257
            }
        }
    

    Of course, I'm not sure I recommend it - but that seems to achieve what you want?

    I also wonder whether you can drop the struct completely and just use unsafe access to a byte[] directly:

        byte[] raw = new byte[] { 1, 0, 0, 0, 1, 1 };
        unsafe
        {
            fixed (byte* addr = raw)
            {
                short* s = (short*)addr;
                Console.WriteLine(s[0]); // should be 1
                Console.WriteLine(s[1]); // should be 0
                Console.WriteLine(s[2]); // should be 257
            }
        }
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题