2 // Tests for Marshal.StructureToPtr and PtrToStructure
6 using System.Runtime.InteropServices;
11 [StructLayout (LayoutKind.Sequential)]
12 public class SimpleObj {
16 public void test () {}
19 [StructLayout (LayoutKind.Sequential)]
20 public struct SimpleStruct2 {
25 [StructLayout (LayoutKind.Sequential, CharSet=CharSet.Ansi)]
26 public struct SimpleStruct {
31 [MarshalAs (UnmanagedType.ByValArray, SizeConst=2)] public short[] a1;
32 [MarshalAs (UnmanagedType.ByValTStr, SizeConst=4)] public string s1;
33 public SimpleStruct2 emb1;
34 public SimpleObj emb2;
37 [MarshalAs (UnmanagedType.ByValArray, SizeConst=2)] public char[] a2;
40 [StructLayout (LayoutKind.Sequential, CharSet=CharSet.Unicode)]
41 public struct ByValWStrStruct {
42 [MarshalAs (UnmanagedType.ByValTStr, SizeConst=4)] public string s1;
46 public unsafe static int Main () {
47 SimpleStruct ss = new SimpleStruct ();
48 int size = Marshal.SizeOf (typeof (SimpleStruct));
53 IntPtr p = Marshal.AllocHGlobal (size);
58 ss.a1 = new short [2];
62 ss.emb1 = new SimpleStruct2 ();
65 ss.emb2 = new SimpleObj ();
68 ss.s2 = "just a test";
74 Marshal.StructureToPtr (ss, p, false);
75 Type t = ss.GetType ();
77 if (Marshal.ReadInt32 (p, (int)Marshal.OffsetOf (t, "a")) != 1)
79 if (Marshal.ReadInt32 (p, (int)Marshal.OffsetOf (t, "bool1")) != 1)
81 if (Marshal.ReadInt32 (p, (int)Marshal.OffsetOf (t, "bool2")) != 0)
83 if (Marshal.ReadInt32 (p, (int)Marshal.OffsetOf (t, "b")) != 2)
85 if (Marshal.ReadInt16 (p, 16) != 6)
87 if (Marshal.ReadInt16 (p, 18) != 5)
89 if (Marshal.ReadByte (p, 20) != 97)
91 if (Marshal.ReadByte (p, 21) != 98)
93 if (Marshal.ReadByte (p, 22) != 99)
95 if (Marshal.ReadByte (p, 23) != 0)
97 if (Marshal.ReadInt32 (p, 24) != 3)
99 if (Marshal.ReadInt32 (p, 28) != 4)
101 if (Marshal.ReadInt32 (p, 32) != 10)
103 if (Marshal.ReadInt32 (p, 36) != 11)
105 if (Marshal.ReadByte (p, (int)Marshal.OffsetOf (t, "a2")) != 97)
107 if (Marshal.ReadByte (p, (int)Marshal.OffsetOf (t, "a2") + 1) != 98)
110 SimpleStruct cp = (SimpleStruct)Marshal.PtrToStructure (p, ss.GetType ());
115 if (cp.bool1 != true)
118 if (cp.bool2 != false)
145 if (cp.s2 != "just a test")
151 if (cp.a2 [0] != 'a')
154 if (cp.a2 [1] != 'b')
157 /* ByValTStr with Unicode */
158 ByValWStrStruct s = new ByValWStrStruct ();
160 IntPtr p2 = Marshal.AllocHGlobal (Marshal.SizeOf (typeof (ByValWStrStruct)));
161 Marshal.StructureToPtr(s, p2, false);
163 /* Check that the ByValWStr is initialized correctly */
164 for (int i = 0; i < 8; ++i)
165 if (Marshal.ReadByte (p2, i) != 0)
171 Marshal.StructureToPtr(s, p2, false);
173 ByValWStrStruct s2 = (ByValWStrStruct)Marshal.PtrToStructure (p2, typeof (ByValWStrStruct));
175 /* The fourth char is lost because of null-termination */