Why does LayoutKind.Sequential work differently if a struct contains a DateTime field?

后端 未结 6 2345
名媛妹妹
名媛妹妹 2020-12-05 07:17

Why does LayoutKind.Sequential work differently if a struct contains a DateTime field?

Consider the following code (a console app which must be compiled with \"unsaf

6条回答
  •  时光取名叫无心
    2020-12-05 08:14

    If you're going to interop with C/C++, I would always be specific with the StructLayout. Instead of Sequential, I would go with Explicit, and specify each position with FieldOffset. In addition, add your Pack variable.

    [StructLayout(LayoutKind.Explicit, Pack=1, CharSet=CharSet.Unicode)]
    public struct Inner
    {
        [FieldOffset(0)]
        public byte First;
        [FieldOffset(1)]
        public double NotFirst;
        [FieldOffset(9)]
        public DateTime WTF;
    }
    

    It sounds like DateTime can't be Marshaled anyhow, only to a string (bingle Marshal DateTime).

    The Pack variable is especially important in C++ code that might be compiled on different systems that have different word sizes.

    I would also ignore the addresses that can be seen when using unsafe code. It doesn't really matter what the compiler does as long as the Marshaling is correct.

提交回复
热议问题