2 using System
.Runtime
.InteropServices
;
6 [StructLayout(LayoutKind
.Sequential
, Size
=32)]
7 public class TestStruct1
12 [StructLayout(LayoutKind
.Sequential
, Size
=32)]
13 public class TestStruct2
15 [MarshalAs(UnmanagedType
.ByValTStr
, SizeConst
=16)]
20 [StructLayout(LayoutKind
.Sequential
, Size
=32)]
21 public class TestStruct3
: TestStruct2
26 [StructLayout (LayoutKind
.Sequential
)]
27 public class TestStruct4
29 [MarshalAs (UnmanagedType
.Interface
)]
33 [StructLayout (LayoutKind
.Sequential
)]
34 public class TestStruct5
36 [MarshalAs (UnmanagedType
.IUnknown
)]
40 [StructLayout (LayoutKind
.Sequential
)]
41 public class TestStruct6
43 [MarshalAs (UnmanagedType
.IDispatch
)]
47 [StructLayout (LayoutKind
.Sequential
)]
48 public class TestStruct7
50 [MarshalAs (UnmanagedType
.Struct
)]
54 public unsafe static int Main ()
57 /// Testing simple struct size
59 if(Marshal
.SizeOf(typeof(TestStruct1
)) != 32)
64 TestStruct1 myStruct
= new TestStruct1();
65 myStruct
.a
= 0x12345678;
67 IntPtr p
= Marshal
.AllocHGlobal(Marshal
.SizeOf(typeof(TestStruct1
)));
68 Marshal
.StructureToPtr(myStruct
, p
, false);
70 Type testType
= typeof(TestStruct1
);
71 if (Marshal
.ReadInt32(p
, (int)Marshal
.OffsetOf(testType
, "a")) != myStruct
.a
)
74 Marshal
.FreeHGlobal(p
);
77 /// Testing struct size with ByValTStr string
79 if(Marshal
.SizeOf(typeof(TestStruct2
)) != 32)
82 TestStruct2 myStruct2
= new TestStruct2();
83 myStruct2
.b
= 0x12345678;
85 p
= Marshal
.AllocHGlobal(Marshal
.SizeOf(typeof(TestStruct2
)));
86 Marshal
.StructureToPtr(myStruct2
, p
, false);
88 Type testType2
= typeof(TestStruct2
);
89 if (Marshal
.ReadInt32(p
, (int)Marshal
.OffsetOf(testType2
, "b")) != myStruct2
.b
)
92 Marshal
.FreeHGlobal(p
);
95 /// Test structure size and struct with inheritance
97 if(Marshal
.SizeOf(typeof(TestStruct3
)) != 64)
100 TestStruct3 myStruct3
= new TestStruct3();
101 myStruct3
.b
= 0x12345678;
102 myStruct3
.c
= 0x76543210;
103 p
= Marshal
.AllocHGlobal(Marshal
.SizeOf(typeof(TestStruct3
)));
104 Marshal
.StructureToPtr(myStruct3
, p
, false);
106 Type testType3
= typeof(TestStruct3
);
108 if(Marshal
.ReadInt32(p
, (int)Marshal
.OffsetOf(testType3
, "b")) != myStruct3
.b
)
111 if (Marshal
.ReadInt32(p
, (int)Marshal
.OffsetOf(testType3
, "c")) != myStruct3
.c
)
114 Marshal
.FreeHGlobal(p
);
117 /// Also make sure OffsetOf returns the correct Exception.
120 Marshal
.OffsetOf(testType3
, "blah");
123 catch(ArgumentException e
) {
130 // test size of structs with objects
131 if (Marshal
.SizeOf (typeof (TestStruct4
)) != IntPtr
.Size
)
133 if (Marshal
.SizeOf (typeof (TestStruct5
)) != IntPtr
.Size
)
135 if (Marshal
.SizeOf (typeof (TestStruct6
)) != IntPtr
.Size
)
138 if (Marshal
.SizeOf (typeof (TestStruct7
)) != 16)