0

Edit: everything bellow applies to Mono/Xamarin, but crashes on .NET with TypeLoadException

When field2 is printed to the stdout I get a new integer each time I run the program. What is the meaning of this value?

class Program
{
    [StructLayout(LayoutKind.Explicit)]
    struct Data
    {
        [FieldOffset(0)]
        public object Field1;

        [FieldOffset(0)]
        public int Field2;
    }

    public static void Main()
    {
        var a = new Data();
        a.Field1 = new object();
        Console.WriteLine(a.Field2);
    }
}
x2bool
  • 2,766
  • 5
  • 26
  • 33
  • Don't you get runtime error when trying to run this? Cause it's illegal to have reference and value type overlap each other like that... – Patryk Spytkowski Jan 08 '16 at 10:45
  • No. There is no runtime error. It compiles and runs just fine. – x2bool Jan 08 '16 at 10:51
  • I'm getting `TypeLoadException` when trying to run your code. The message states: _Could not load type Test.Data' from assembly 'Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because it contains an object field at offset 0 that is incorrectly aligned or overlapped by a non-object field._ Which is by design, as you shouldn't overlap reference and value types. – Patryk Spytkowski Jan 08 '16 at 10:58
  • [Like here...](http://stackoverflow.com/questions/1182782/c-sharp-structlayout-explicit-question) – Patryk Spytkowski Jan 08 '16 at 11:03
  • Hm... maybe this is because I am using Mono to run this code. I'll check. – x2bool Jan 08 '16 at 11:11
  • Interesting... Maybe. As Dmitry answered value of the int field would be an address (on 32 bit system, on 64 bit just half :) ) of your `Object`. Overlaping reference and value types is security concern as you could easily corrupt data in your application heap. – Patryk Spytkowski Jan 08 '16 at 11:21

1 Answers1

1

It's a pointer.
IMO, you should avoid using reference type fields in explicitly layouted structs.

Dmitry
  • 13,797
  • 6
  • 32
  • 48