C#StructLayout Pack得到System.NullReferenceException,对齐问题?

时间:2014-03-07 14:29:16

标签: c# mono unity3d structlayout

首先,我会说,我没有被卡住,因为我有很多解决方法! 最好的是我不再需要1Byte Pack了:P

但说实话,我对这种行为感到很困惑。 我正在使用Unity,它在Windows上完美运行但在Android(单声道)上失败

  • 我写了一些无效的东西吗?
  • 我是否在Mono上犯了错误?!

明确欢迎评论!!

public class TEST
{
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    private struct MyStruct {
        public float   field1;
        public float   field2;
    };

    //This order sucess on windows, but failed on android
    private byte oneByte = 0x00;
    private MyStruct mMyStruct;


    public bool doTest()
    {
        try {
            mMyStruct.field1  = (oneByte++);
        } catch {
            // System.NullReferenceException: Object reference not set to an instance of an object
            return false;
        }
        return true;
    }           
}

一些额外的信息/线索:

  • Android / Windows之间的差异可能来自处理器架构的差异 Android ARM(RISC),假设4Bytes alignement(或拇指模式下至少2Bytes)

  • [StructLayout(LayoutKind.Sequential,Pack = 1)]似乎影响的不仅仅是结构。

内存对齐可能变为:

[ onByte    ]  [ field1 #0 ] [ field1 #1 ] [ field1 #2 ]
[ field1 #3 ]  [ field2 #1 ] [ field2 #1 ] [ field2 #3 ]
[ field2 #4 ]  [ *pad*     ] [ *pad*     ] [ *pad*     ]

我的预期更像这样:

[ onByte    ] [ *pad*     ] [ *pad*     ] [ *pad*     ]
[ field1 #0 ] [ field1 #1 ] [ field1 #2 ] [ field1 #3 ]
[ field2 #1 ] [ field2 #1 ] [ field2 #3 ][ field2 #4 ] 

0 个答案:

没有答案