Bypassing C#'s type safeguards and storing an Integer in a String

后端 未结 1 601
醉梦人生
醉梦人生 2021-01-23 09:14

Have a look at the following code:

static void Main(string[] args)
{
    string s = null;
    string[] myArray = new string[1];

    { } // do something evil her         


        
相关标签:
1条回答
  • 2021-01-23 09:46

    One technique is using LayoutKind.Explicit to implement a union which can be used to reinterpret cast an arbitrary object to string. First box an int, then assign it to the object field of the union and then read out the string field.

    [StructLayout(LayoutKind.Explicit)]
    public struct Evil
    {
        [FieldOffset(0)]
        public string s;
    
        [FieldOffset(0)]
        public object o;
    }
    
    string ReinterpretCastToString(object o)
    {
        Evil evil=new Evil();
        evil.o=o;
        return evil.s;
    }
    
    void Main()
    {
        string s = ReinterpretCastToString(1);
    
        if (s.GetType() == typeof(int))
        {
            Console.WriteLine("This should not happen!"); 
        }
    }
    

    This is most likely undefined behavior that may stop working at any time. Obviously you shouldn't use this in a real program.

    0 讨论(0)
提交回复
热议问题