Boolean Marshalling with LayoutKind.Explicit, Is this broken or failing as designed?

前端 未结 3 1988
天命终不由人
天命终不由人 2021-01-06 02:27

First of all the Boolean type is said to have a default marshal type of a four-byte value. So the following code works:

    struct A 
    { 
        public          


        
3条回答
  •  再見小時候
    2021-01-06 03:04

    It is working as designed.

    Here is what is happening:

    Take the new int[] { 2, 4 } and lets marshal it into A, B, Broken, and Broken2. The last is the same as Broken, but with fields' order reversed (first b, then a).

    If we marshal the ints into these structures we get the following values in memory:

    • A: 1, 4
    • B: 2, 1
    • Broken: 2, 1
    • Broken2: 1, 4

    So what is happening is the following:

    • When the marshaller encounters a boolean, the value of it is: bool = (original != 0);
    • When there are two fields that map into the same memory, the rules of the last field win

    So for A, the first int gets converted to 1, for B, the second int gets converted to 1, for Broken, since B is the last field, its rules apply, and hence the second int gets converted to 1. Similarly for Broken2.

提交回复
热议问题