Strange behavior

I wrote a small piece of code to demonstrate this problem. The problem is that when I declare a structure with a state, Layout.Explicit it assigns undefined values ​​to the fields of this structure depending on another value. This problem only occurs when using state Layout.Explicit. this is pretty hard to explain without code, so here is a short example.

using System.Runtime.InteropServices;
namespace ConsoleStruct
{
    class Program
    {
        [StructLayout(LayoutKind.Explicit)]
        struct TestStruct
        {
            [FieldOffset(0)]
            public double dbl;
            [FieldOffset(0)]
            public ulong uu;
        }

        public static void SimpleMethod()
        {
            TestStruct st;
            st.uu = 0;
            st.dbl = 5000.0;
            Console.WriteLine(st.uu.ToString()); // ==> uu becomes 4662219572839972864 
                                                 //instead of 0 :(
                                                 // it looks like the value of uu is dependent on the 
                                                 //value assigned to dbl
            Console.ReadLine();
        }
        static void Main(string[] args)
        {
            SimpleMethod();
        }
    }
}

Can someone explain to me why this is happening. Using VS 2013. Thanks.

+4
source share
1 answer

it looks like the uu value depends on the value assigned by dbl

Yes it is. Since you gave them the same bias, they occupy the same place in memory (inside the structure).

[FieldOffset(...)] , . API .

, - (, ) . , .

+8

Source: https://habr.com/ru/post/1609089/


All Articles