[System] Tweak socket test
[mono-project.git] / mono / tests / marshal8.cs
blobf96bf5090954bfb1f9ae43778f453fabdff02f2e
1 using System;
2 using System.Runtime.InteropServices;
5 [StructLayout(LayoutKind.Sequential, Size=1024)]
6 public class Dummy {
7 [MarshalAs(UnmanagedType.ByValArray, SizeConst=16)]
8 public byte[] a;
10 [MarshalAs(UnmanagedType.ByValArray, SizeConst=16)]
11 public float[] b;
13 [MarshalAs(UnmanagedType.ByValArray, SizeConst=16)]
14 public long[] c;
17 [StructLayout(LayoutKind.Sequential)]
18 class FormattedClass
20 public int i;
22 public FormattedClass(int i)
24 this.i = i;
28 [StructLayout(LayoutKind.Sequential)]
29 struct Struct
31 public int i;
33 public Struct(int i)
35 this.i = i;
39 public class X {
40 public static unsafe int Main () {
42 ///
43 /// Structure to pointer
44 ///
46 Dummy dummy = new Dummy ();
47 dummy.a = new byte[16];
48 dummy.b = new float[16];
49 dummy.c = new long[16];
51 for(int i=0; i<16; i++)
52 dummy.a[i] = (byte)(dummy.b[i] = dummy.c[i] = i+1);
54 IntPtr p = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Dummy)));
55 Marshal.StructureToPtr(dummy, p, false);
57 int offset = (int)Marshal.OffsetOf(typeof(Dummy), "a");
58 byte *data1 = (byte*)p.ToPointer() + offset;
59 for(int i=0; i<16; i++) {
60 if(data1[i] != i+1)
61 return 1;
64 offset = (int)Marshal.OffsetOf(typeof(Dummy), "b");
65 float *data2 = (float*)((byte*)p.ToPointer() + offset);
66 for(int i=0; i<16; i++)
67 if(data2[i] != i+1)
68 return 2;
70 offset = (int)Marshal.OffsetOf(typeof(Dummy), "c");
71 long *data3 = (long*)((byte*)p.ToPointer() + offset);
72 for(int i=0; i<16; i++)
73 if(data3[i] != i+1)
74 return 3;
76 ///
77 /// Pointer to structure
78 ///
79 Dummy dummy2 = new Dummy ();
80 Marshal.PtrToStructure(p, dummy2);
82 if(dummy2.a.Length != dummy.a.Length) return 4;
83 if(dummy2.b.Length != dummy.b.Length) return 5;
84 if(dummy2.c.Length != dummy.c.Length) return 6;
86 for(int i=0; i<16; i++)
88 if(dummy2.a[i] != i+1) return 7;
89 if(dummy2.b[i] != i+1) return 8;
90 if(dummy2.c[i] != i+1) return 9;
93 Marshal.FreeHGlobal(p);
96 ///
97 /// Only allow
98 ///
99 FormattedClass fc = new FormattedClass(20);
100 IntPtr fc_ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(FormattedClass)));
101 Marshal.StructureToPtr(fc, fc_ptr, false);
102 Marshal.PtrToStructure(fc_ptr, fc);
103 if (fc.i != 20)
104 return 10;
105 Marshal.FreeHGlobal(fc_ptr);
107 bool exception = false;
110 object str = new Struct(20);
111 IntPtr str_ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Struct)));
112 Marshal.StructureToPtr(str, str_ptr, false);
113 Marshal.PtrToStructure(str_ptr, str);
114 Marshal.FreeHGlobal(str_ptr);
116 catch (Exception ex)
118 exception = true;
120 if (!exception)
121 return 11;
123 return 0;