2005-01-31 Zoltan Varga <vargaz@freemail.hu>
[mono.git] / mono / tests / marshal8.cs
1 using System;
2 using System.Runtime.InteropServices;
3
4
5 [StructLayout(LayoutKind.Sequential, Size=1024)]
6 public class Dummy {
7         [MarshalAs(UnmanagedType.ByValArray, SizeConst=16)]
8         public byte[]   a;
9
10         [MarshalAs(UnmanagedType.ByValArray, SizeConst=16)]
11         public float[]  b;
12
13         [MarshalAs(UnmanagedType.ByValArray, SizeConst=16)]
14         public long[]   c;
15 }
16
17 public class X {
18         public static unsafe int Main () {
19
20                 ///
21                 ///     Structure to pointer
22                 ///
23
24                 Dummy dummy = new Dummy ();
25                 dummy.a = new byte[16];
26                 dummy.b = new float[16];
27                 dummy.c = new long[16];
28
29                 for(int i=0; i<16; i++)
30                         dummy.a[i] = (byte)(dummy.b[i] = dummy.c[i] = i+1);
31
32                 IntPtr p = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Dummy)));
33                 Marshal.StructureToPtr(dummy, p, false);
34
35                 int offset = (int)Marshal.OffsetOf(typeof(Dummy), "a");
36                 byte *data1 = (byte*)p.ToPointer() + offset;
37                 for(int i=0; i<16; i++) {
38                         if(data1[i] != i+1)
39                                 return 1;
40                 }
41                 
42                 offset = (int)Marshal.OffsetOf(typeof(Dummy), "b");
43                 float *data2 = (float*)((byte*)p.ToPointer() + offset);
44                 for(int i=0; i<16; i++)
45                         if(data2[i] != i+1)
46                                 return 2;
47
48                 offset = (int)Marshal.OffsetOf(typeof(Dummy), "c");
49                 long *data3 = (long*)((byte*)p.ToPointer() + offset);
50                 for(int i=0; i<16; i++)
51                         if(data3[i] != i+1)
52                                 return 3;
53
54                 ///
55                 ///     Pointer to structure
56                 ///
57                 Dummy dummy2 = new Dummy ();
58                 Marshal.PtrToStructure(p, dummy2);
59
60                 if(dummy2.a.Length != dummy.a.Length) return 4;
61                 if(dummy2.b.Length != dummy.b.Length) return 5;
62                 if(dummy2.c.Length != dummy.c.Length) return 6;
63
64                 for(int i=0; i<16; i++)
65                 {
66                         if(dummy2.a[i] != i+1) return 7;
67                         if(dummy2.b[i] != i+1) return 8;
68                         if(dummy2.c[i] != i+1) return 9;
69                 }
70
71                 Marshal.FreeHGlobal(p);
72
73                 return 0;
74         }
75 }