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

后端 未结 6 2336
名媛妹妹
名媛妹妹 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:07

    You're checking the addresses as they are within the managed structure. Marshal attributes have no guarantees for the arrangement of fields within managed structures.

    The reason it marshals correctly into native structures, is because the data is copied into native memory using the attributes set by marshal values.

    So, the arrangement of the managed structure has no impact on the arranged of the native structure. Only the attributes affect the arrangement of native structure.

    If fields setup with marshal attributes were stored in managed data the same way as native data, then there would be no point in Marshal.StructureToPtr, you'd simply byte-copy the data over.

提交回复
热议问题