Welcome to mirror list, hosted at ThFree Co, Russian Federation.

PInvoke.cs « PInvoke « Simple « src « tests - github.com/mono/corert.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 29e2def9205e9e0b2089fa7b80fd898685dfdae6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;

// Make sure the interop data are present even without reflection
namespace System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.All)]
    internal class __BlockAllReflectionAttribute : Attribute { }
}

// Name of namespace matches the name of the assembly on purpose to
// ensure that we can handle this (mostly an issue for C++ code generation).
namespace PInvokeTests
{
    internal class Program
    {
        [DllImport("*", CallingConvention = CallingConvention.StdCall)]
        private static extern int Square(int intValue);

        [DllImport("*", CallingConvention = CallingConvention.StdCall)]
        private static extern int IsTrue(bool boolValue);

        [DllImport("*", CallingConvention = CallingConvention.StdCall)]
        private static extern int CheckIncremental(int[] array, int sz);

        [DllImport("*", CallingConvention = CallingConvention.StdCall)]
        private static extern int CheckIncremental_Foo(Foo[] array, int sz);

        [DllImport("*", CallingConvention = CallingConvention.StdCall)]
        private static extern int Inc(ref int value);

        [DllImport("*", CallingConvention = CallingConvention.StdCall)]
        private static extern int VerifyByRefFoo(ref Foo value);

        [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
        private static extern bool GetNextChar(ref char c);

        [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
        private static extern int VerifyAnsiString(string str);

        [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
        private static extern int VerifyAnsiStringOut(out string str);

        [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
        private static extern int VerifyAnsiStringRef(ref string str);

        [DllImport("*", EntryPoint = "VerifyAnsiStringRef", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
        private static extern int VerifyAnsiStringInRef([In]ref string str);

        [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
        private static extern int VerifyUnicodeString(string str);

        [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
        private static extern int VerifyUnicodeStringOut(out string str);

        [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
        private static extern int VerifyUnicodeStringRef(ref string str);

        [DllImport("*", EntryPoint = "VerifyUnicodeStringRef", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
        private static extern int VerifyUnicodeStringInRef([In]ref string str);

        [DllImport("*", CharSet = CharSet.Ansi)]
        private static extern int VerifyAnsiStringArray([In, MarshalAs(UnmanagedType.LPArray)]string[] str);

        [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
        private static extern bool VerifyAnsiCharArrayIn(char[] a);

        [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
        private static extern bool VerifyAnsiCharArrayOut([Out]char[] a);

        [DllImport("*", CharSet = CharSet.Ansi)]
        private static extern void ToUpper([In, Out, MarshalAs(UnmanagedType.LPArray)]string[] str);

        [DllImport("*", CharSet = CharSet.Ansi)]
        private static extern bool VerifySizeParamIndex(
                [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] out byte[] arrByte, out byte arrSize);

        [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, EntryPoint = "VerifyUnicodeStringBuilder")]
        private static extern int VerifyUnicodeStringBuilder(StringBuilder sb);

        [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, EntryPoint = "VerifyUnicodeStringBuilder")]
        private static extern int VerifyUnicodeStringBuilderIn([In]StringBuilder sb);

        [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
        private static extern int VerifyUnicodeStringBuilderOut([Out]StringBuilder sb);

        [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi, EntryPoint = "VerifyAnsiStringBuilder")]
        private static extern int VerifyAnsiStringBuilder(StringBuilder sb);

        [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi, EntryPoint = "VerifyAnsiStringBuilder")]
        private static extern int VerifyAnsiStringBuilderIn([In]StringBuilder sb);

        [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
        private static extern int VerifyAnsiStringBuilderOut([Out]StringBuilder sb);

        [DllImport("*", CallingConvention = CallingConvention.StdCall)]
        public static extern bool SafeHandleTest(SafeMemoryHandle sh1, Int64 sh1Value);

        [DllImport("*", CallingConvention = CallingConvention.StdCall)]
        public static extern int SafeHandleOutTest(out SafeMemoryHandle sh1);

        [DllImport("*", CallingConvention = CallingConvention.StdCall)]
        public static extern int SafeHandleRefTest(ref SafeMemoryHandle sh1, bool change);

        [DllImport("*", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
        public static extern bool LastErrorTest();

        delegate int Delegate_Int(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j);
        [DllImport("*", CallingConvention = CallingConvention.StdCall)]
        static extern bool ReversePInvoke_Int(Delegate_Int del);

        delegate int Delegate_Int_AggressiveInlining(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j);
        [DllImport("*", CallingConvention = CallingConvention.StdCall, EntryPoint = "ReversePInvoke_Int")]
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        static extern bool ReversePInvoke_Int_AggressiveInlining(Delegate_Int_AggressiveInlining del);

        [UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet=CharSet.Ansi)]
        delegate bool Delegate_String(string s);
        [DllImport("*", CallingConvention = CallingConvention.StdCall)]
        static extern bool ReversePInvoke_String(Delegate_String del);

        [DllImport("*", CallingConvention = CallingConvention.StdCall)]
        static extern Delegate_String GetDelegate();

        [DllImport("*", CallingConvention = CallingConvention.StdCall)]
        static extern bool Callback(ref Delegate_String d);

        delegate void Delegate_Unused();
        [DllImport("*", CallingConvention = CallingConvention.StdCall)]
        static extern unsafe int* ReversePInvoke_Unused(Delegate_Unused del);

        [DllImport("*", CallingConvention = CallingConvention.StdCall, EntryPoint = "StructTest")]
        static extern bool StructTest_Auto(AutoStruct ss);

        [DllImport("*", CallingConvention = CallingConvention.StdCall)]
        static extern bool StructTest_Sequential2(NesterOfSequentialStruct.SequentialStruct ss);

        [DllImport("*", CallingConvention = CallingConvention.StdCall)]
        static extern bool StructTest(SequentialStruct ss);

        [DllImport("*", CallingConvention = CallingConvention.StdCall)]
        static extern void StructTest_ByRef(ref SequentialStruct ss);

        [DllImport("*", CallingConvention = CallingConvention.StdCall)]
        static extern void StructTest_ByOut(out SequentialStruct ss);

        [DllImport("*", CallingConvention = CallingConvention.StdCall)]
        static extern bool StructTest_Explicit(ExplicitStruct es);

        [DllImport("*", CallingConvention = CallingConvention.StdCall)]
        static extern bool StructTest_Nested(NestedStruct ns);

        [DllImport("*", CallingConvention = CallingConvention.StdCall)]
        static extern bool StructTest_Array(SequentialStruct []ns, int length);

        [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
        static extern bool IsNULL(char[] a);

        [DllImport("*", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
        static extern bool IsNULL(String sb);

        [DllImport("*", CallingConvention = CallingConvention.StdCall)]
        static extern bool IsNULL(Foo[] foo);

        [DllImport("*", CallingConvention = CallingConvention.StdCall)]
        static extern bool IsNULL(SequentialStruct[] foo);

        [StructLayout(LayoutKind.Sequential, CharSet= CharSet.Ansi, Pack = 4)]
        public unsafe struct InlineArrayStruct
        {
            public int f0;
            public int f1;
            public int f2;

            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
            public short[] inlineArray;

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 11)]
            public string inlineString;
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 4)]
        public unsafe struct InlineUnicodeStruct
        {
            public int f0;

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 11)]
            public string inlineString;
        }

        [DllImport("*", CallingConvention = CallingConvention.StdCall)]
        static extern bool InlineArrayTest(ref InlineArrayStruct ias, ref InlineUnicodeStruct ius);

        [UnmanagedFunctionPointer(CallingConvention.Cdecl, SetLastError = true)]
        public unsafe delegate void SetLastErrorFuncDelegate(int errorCode);

        [DllImport("*", CallingConvention = CallingConvention.StdCall)]
        internal static extern IntPtr GetFunctionPointer();


        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
        internal unsafe struct InlineString
        {
            internal uint size;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            internal string name;
        }

        [DllImport("*", CallingConvention = CallingConvention.StdCall)]
        static extern bool InlineStringTest(ref InlineString ias);

        internal delegate int Callback0();
        internal delegate int Callback1();
        internal delegate int Callback2();

        [DllImport("*")]
        internal static extern bool RegisterCallbacks(ref Callbacks callbacks);

        [StructLayout(LayoutKind.Sequential)]
        internal struct Callbacks
        {
            public Callback0 callback0;
            public Callback1 callback1;
            public Callback2 callback2;
        }

        public static int callbackFunc0() { return 0; }
        public static int callbackFunc1() { return 1; }
        public static int callbackFunc2() { return 2; }

        public static int Main(string[] args)
        {
            TestBlittableType();
            TestBoolean();
            TestUnichar();
            TestArrays();
            TestByRef();
            TestString();
            TestStringBuilder();
            TestLastError();
            TestSafeHandle();
            TestStringArray();
            TestSizeParamIndex();
#if !CODEGEN_CPP
            TestDelegate();
            TestStruct();
            TestMarshalStructAPIs();
#endif            
            return 100;
        }

        public static void ThrowIfNotEquals<T>(T expected, T actual, string message)
        {
            if (!expected.Equals(actual))
            {
                message += "\nExpected: " + expected.ToString() + "\n";
                message += "Actual: " + actual.ToString() + "\n";
                throw new Exception(message);
            }
        }

        public static void ThrowIfNotEquals(bool expected, bool actual, string message)
        {
            ThrowIfNotEquals(expected ? 1 : 0, actual ? 1 : 0, message);
        }

        private static void TestBlittableType()
        {
            Console.WriteLine("Testing marshalling blittable types");
            ThrowIfNotEquals(100, Square(10), "Int marshalling failed");
        }

        private static void TestBoolean()
        {
            Console.WriteLine("Testing marshalling boolean");
            ThrowIfNotEquals(1, IsTrue(true), "Bool marshalling failed");
            ThrowIfNotEquals(0, IsTrue(false), "Bool marshalling failed");
        }

        private static void TestUnichar()
        {
            Console.WriteLine("Testing Unichar");
            char c = 'a';
            ThrowIfNotEquals(true, GetNextChar(ref c), "Unichar marshalling failed.");
            ThrowIfNotEquals('b', c, "Unichar marshalling failed.");
        }

        struct Foo
        {
            public int a;
            public float b;
        }

        private static void TestArrays()
        {
            Console.WriteLine("Testing marshalling int arrays");

            const int ArraySize = 100;
            int[] arr = new int[ArraySize];
            for (int i = 0; i < ArraySize; i++)
                arr[i] = i;

            ThrowIfNotEquals(0, CheckIncremental(arr, ArraySize), "Array marshalling failed");

            Console.WriteLine("Testing marshalling blittable struct arrays");

            Foo[] arr_foo = null;
            ThrowIfNotEquals(true, IsNULL(arr_foo), "Blittable array null check failed");
            
            arr_foo = new Foo[ArraySize];
            for (int i = 0; i < ArraySize; i++)
            {
                arr_foo[i].a = i;
                arr_foo[i].b = i;
            }

            ThrowIfNotEquals(0, CheckIncremental_Foo(arr_foo, ArraySize), "Array marshalling failed");

            char[] a = "Hello World".ToCharArray();
            ThrowIfNotEquals(true, VerifyAnsiCharArrayIn(a), "Ansi Char Array In failed");

            char[] b = new char[12];
            ThrowIfNotEquals(true, VerifyAnsiCharArrayOut(b), "Ansi Char Array Out failed");
            ThrowIfNotEquals("Hello World!", new String(b), "Ansi Char Array Out failed2");

            char[] c = null;
            ThrowIfNotEquals(true, IsNULL(c), "AnsiChar Array null check failed");
        }

        private static void TestByRef()
        {
            Console.WriteLine("Testing marshalling by ref");

            int value = 100;
            ThrowIfNotEquals(0, Inc(ref value), "By ref marshalling failed");
            ThrowIfNotEquals(101, value, "By ref marshalling failed");

            Foo foo = new Foo();
            foo.a = 10;
            foo.b = 20;
            int ret = VerifyByRefFoo(ref foo);
            ThrowIfNotEquals(0, ret, "By ref struct marshalling failed");

            ThrowIfNotEquals(foo.a, 11, "By ref struct unmarshalling failed");
            ThrowIfNotEquals(foo.b, 21.0f, "By ref struct unmarshalling failed");
        }

        private static void TestString()
        {
            Console.WriteLine("Testing marshalling string");
            ThrowIfNotEquals(1, VerifyAnsiString("Hello World"), "Ansi String marshalling failed.");
            ThrowIfNotEquals(1, VerifyUnicodeString("Hello World"), "Unicode String marshalling failed.");
            string s;
            ThrowIfNotEquals(1, VerifyAnsiStringOut(out s), "Out Ansi String marshalling failed");
            ThrowIfNotEquals("Hello World", s, "Out Ansi String marshalling failed");

            VerifyAnsiStringInRef(ref s);
            ThrowIfNotEquals("Hello World", s, "In Ref ansi String marshalling failed");

            VerifyAnsiStringRef(ref s);
            ThrowIfNotEquals("Hello World!", s, "Ref ansi String marshalling failed");

            ThrowIfNotEquals(1, VerifyUnicodeStringOut(out s), "Out Unicode String marshalling failed");
            ThrowIfNotEquals("Hello World", s, "Out Unicode String marshalling failed");

            VerifyUnicodeStringInRef(ref s);
            ThrowIfNotEquals("Hello World", s, "In Ref Unicode String marshalling failed");

            VerifyUnicodeStringRef(ref s);
            ThrowIfNotEquals("Hello World!", s, "Ref Unicode String marshalling failed");

            string ss = null;
            ThrowIfNotEquals(true, IsNULL(ss), "Ansi String null check failed");
        
        }

        private static void TestStringBuilder()
        {
            Console.WriteLine("Testing marshalling string builder");
            StringBuilder sb = new StringBuilder("Hello World");
            ThrowIfNotEquals(1, VerifyUnicodeStringBuilder(sb), "Unicode StringBuilder marshalling failed");
            ThrowIfNotEquals("HELLO WORLD", sb.ToString(), "Unicode StringBuilder marshalling failed.");

            StringBuilder sb1 = null;
            // for null stringbuilder it should return -1
            ThrowIfNotEquals(-1, VerifyUnicodeStringBuilder(sb1), "Null unicode StringBuilder marshalling failed");

            StringBuilder sb2 = new StringBuilder("Hello World");
            ThrowIfNotEquals(1, VerifyUnicodeStringBuilderIn(sb2), "In unicode StringBuilder marshalling failed");
            // Only [In] should change stringbuilder value
            ThrowIfNotEquals("Hello World", sb2.ToString(), "In unicode StringBuilder marshalling failed");

            StringBuilder sb3 = new StringBuilder();
            ThrowIfNotEquals(1, VerifyUnicodeStringBuilderOut(sb3), "Out Unicode string marshalling failed");
            ThrowIfNotEquals("Hello World", sb3.ToString(), "Out Unicode StringBuilder marshalling failed");

            StringBuilder sb4 = new StringBuilder("Hello World");
            ThrowIfNotEquals(1, VerifyAnsiStringBuilder(sb4), "Ansi StringBuilder marshalling failed");
            ThrowIfNotEquals("HELLO WORLD", sb4.ToString(), "Ansi StringBuilder marshalling failed.");

            StringBuilder sb5 = null;
            // for null stringbuilder it should return -1
            ThrowIfNotEquals(-1, VerifyAnsiStringBuilder(sb5), "Null Ansi StringBuilder marshalling failed");

            StringBuilder sb6 = new StringBuilder("Hello World");
            ThrowIfNotEquals(1, VerifyAnsiStringBuilderIn(sb6), "In unicode StringBuilder marshalling failed");
            // Only [In] should change stringbuilder value
            ThrowIfNotEquals("Hello World", sb6.ToString(), "In unicode StringBuilder marshalling failed");

            StringBuilder sb7 = new StringBuilder();
            ThrowIfNotEquals(1, VerifyAnsiStringBuilderOut(sb7), "Out Ansi string marshalling failed");
            ThrowIfNotEquals("Hello World!", sb7.ToString(), "Out Ansi StringBuilder marshalling failed");
        }


        private static void TestStringArray()
        {
            Console.WriteLine("Testing marshalling string array");
            string[] strArray = new string[] { "Hello", "World" };
            ThrowIfNotEquals(1, VerifyAnsiStringArray(strArray), "Ansi string array in marshalling failed.");
            ToUpper(strArray);

            ThrowIfNotEquals(true, "HELLO" == strArray[0] && "WORLD" == strArray[1], "Ansi string array  out marshalling failed.");
        }

        private static void TestLastError()
        {
            Console.WriteLine("Testing last error");
            ThrowIfNotEquals(true, LastErrorTest(), "GetLastWin32Error is not zero");
            ThrowIfNotEquals(12345, Marshal.GetLastWin32Error(), "Last Error test failed");
        }

        private static void TestSafeHandle()
        {
            Console.WriteLine("Testing marshalling SafeHandle");

            SafeMemoryHandle hnd = SafeMemoryHandle.AllocateMemory(1000);

            IntPtr hndIntPtr = hnd.DangerousGetHandle(); //get the IntPtr associated with hnd
            long val = hndIntPtr.ToInt64(); //return the 64-bit value associated with hnd

            ThrowIfNotEquals(true, SafeHandleTest(hnd, val), "SafeHandle marshalling failed.");

            Console.WriteLine("Testing marshalling out SafeHandle");
            SafeMemoryHandle hnd2;
            int actual = SafeHandleOutTest(out hnd2);
            int expected = unchecked((int)hnd2.DangerousGetHandle().ToInt64());
            ThrowIfNotEquals(actual, expected, "SafeHandle out marshalling failed");

            Console.WriteLine("Testing marshalling ref SafeHandle");
            SafeMemoryHandle hndOriginal = hnd2;
            SafeHandleRefTest(ref hnd2, false);
            ThrowIfNotEquals(hndOriginal, hnd2, "SafeHandle no-op ref marshalling failed");

            int actual3 = SafeHandleRefTest(ref hnd2, true);
            int expected3 = unchecked((int)hnd2.DangerousGetHandle().ToInt64());
            ThrowIfNotEquals(actual3, expected3, "SafeHandle ref marshalling failed");

            hndOriginal.Dispose();
            hnd2.Dispose();
        }

        private static void TestSizeParamIndex()
        {
            Console.WriteLine("Testing SizeParamIndex");
            byte byte_Array_Size;
            byte[] arrByte;

            VerifySizeParamIndex(out arrByte, out byte_Array_Size);
            ThrowIfNotEquals(10, byte_Array_Size, "out size failed.");
            bool pass = true;
            for (int i = 0; i < byte_Array_Size; i++)
            {
                if (arrByte[i] != i)
                {
                    pass = false;
                    break;
                }
            }
            ThrowIfNotEquals(true, pass, "SizeParamIndex failed.");
        }

        private class ClosedDelegateCLass
        {
            public int Sum(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j)
            {
                return a + b + c + d + e + f + g + h + i + j;
            }

            public bool GetString(String s)
            {
                return s == "Hello World";
            }
        }

        private static void TestDelegate()
        {
            Console.WriteLine("Testing Delegate");

            Delegate_Int del = new Delegate_Int(Sum);
            ThrowIfNotEquals(true, ReversePInvoke_Int(del), "Delegate marshalling failed.");

            Delegate_Int_AggressiveInlining del_aggressive = new Delegate_Int_AggressiveInlining(Sum);
            ThrowIfNotEquals(true, ReversePInvoke_Int_AggressiveInlining(del_aggressive), "Delegate marshalling with aggressive inlining failed.");

            unsafe
            {
                //
                // We haven't instantiated Delegate_Unused and nobody
                // allocates it. If a EEType is not constructed for Delegate_Unused
                // it will fail during linking.
                //
                ReversePInvoke_Unused(null);
            }

            Delegate_Int closed = new Delegate_Int((new ClosedDelegateCLass()).Sum);
            ThrowIfNotEquals(true, ReversePInvoke_Int(closed), "Closed Delegate marshalling failed.");

            Delegate_String ret = GetDelegate();
            ThrowIfNotEquals(true, ret("Hello World!"), "Delegate as P/Invoke return failed");

            Delegate_String d = new Delegate_String(new ClosedDelegateCLass().GetString);
            ThrowIfNotEquals(true, Callback(ref d), "Delegate IN marshalling failed");
            ThrowIfNotEquals(true, d("Hello World!"), "Delegate OUT marshalling failed");

            Delegate_String ds = new Delegate_String((new ClosedDelegateCLass()).GetString);
            ThrowIfNotEquals(true, ReversePInvoke_String(ds), "Delegate marshalling failed.");

            IntPtr procAddress = GetFunctionPointer();
            SetLastErrorFuncDelegate funcDelegate =
                Marshal.GetDelegateForFunctionPointer<SetLastErrorFuncDelegate>(procAddress);
            funcDelegate(0x204);
            ThrowIfNotEquals(0x204, Marshal.GetLastWin32Error(), "Not match");
        }

        static int Sum(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j)
        {
            return a + b + c + d + e + f + g + h + i + j;
        }
        [StructLayout(LayoutKind.Auto)]
        public struct AutoStruct
        {
            public short f0;
            public int f1;
            public float f2;
            [MarshalAs(UnmanagedType.LPStr)]
            public String f3;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct SequentialStruct
        {
            public short f0;
            public int f1;
            public float f2;
            [MarshalAs(UnmanagedType.LPStr)]
            public String f3;
        }

        // A second struct with the same name but nested. Regression test against native types being mangled into
        // the compiler-generated type and losing fully qualified type name information.
        class NesterOfSequentialStruct
        {
            [StructLayout(LayoutKind.Sequential)]
            public struct SequentialStruct
            {
                public float f1;
                public int f2;
            }
        }

        [StructLayout(LayoutKind.Explicit)]
        public struct ExplicitStruct
        {
            [FieldOffset(0)]
            public int f1;

            [FieldOffset(12)]
            public float f2;

            [FieldOffset(24)]
            [MarshalAs(UnmanagedType.LPStr)]
            public String f3;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct NestedStruct
        {
            public int f1;

            public ExplicitStruct f2;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct NonBlittableStruct
        {
            public int f1;
            public bool f2;
            public bool f3;
            public bool f4;
        }

        [StructLayout(LayoutKind.Sequential)]
        public class BlittableClass
        {
            public long f1;
            public int f2;
            public int f3;
            public long f4;
        }

        [StructLayout(LayoutKind.Sequential)]
        public class NonBlittableClass
        {
            public bool f1;
            public bool f2;
            public int f3;
        }

        private static void TestStruct()
        {
            Console.WriteLine("Testing Structs");
            SequentialStruct ss = new SequentialStruct();
            ss.f0 = 100;
            ss.f1 = 1;
            ss.f2 = 10.0f;
            ss.f3 = "Hello";

            ThrowIfNotEquals(true, StructTest(ss), "Struct marshalling scenario1 failed.");

            StructTest_ByRef(ref ss);
            ThrowIfNotEquals(true,  ss.f1 == 2 && ss.f2 == 11.0 && ss.f3.Equals("Ifmmp"), "Struct marshalling scenario2 failed.");

            SequentialStruct ss2 = new SequentialStruct();
            StructTest_ByOut(out ss2);
            ThrowIfNotEquals(true, ss2.f0 == 1 && ss2.f1 == 1.0 &&  ss2.f2 == 1.0 && ss2.f3.Equals("0123456"), "Struct marshalling scenario3 failed.");

            NesterOfSequentialStruct.SequentialStruct ss3 = new NesterOfSequentialStruct.SequentialStruct();
            ss3.f1 = 10.0f;
            ss3.f2 = 123;

            ThrowIfNotEquals(true, StructTest_Sequential2(ss3), "Struct marshalling scenario1 failed.");

            ExplicitStruct es = new ExplicitStruct();
            es.f1 = 100;
            es.f2 = 100.0f;
            es.f3 = "Hello";
            ThrowIfNotEquals(true, StructTest_Explicit(es), "Struct marshalling scenario4 failed.");

            NestedStruct ns = new NestedStruct();
            ns.f1 = 100;
            ns.f2 = es;
            ThrowIfNotEquals(true, StructTest_Nested(ns), "Struct marshalling scenario5 failed.");

            SequentialStruct[] ssa = null;
            ThrowIfNotEquals(true, IsNULL(ssa), "Non-blittable array null check failed");

            ssa = new SequentialStruct[3];
            for (int i = 0; i < 3; i++)
            {
                ssa[i].f1 = 0;
                ssa[i].f1 = i;
                ssa[i].f2 = i*i;
                ssa[i].f3 = i.LowLevelToString(); 
            }
            ThrowIfNotEquals(true, StructTest_Array(ssa, ssa.Length), "Array of struct marshalling failed");

            InlineString ils = new InlineString();
            InlineStringTest(ref ils);
            ThrowIfNotEquals("Hello World!", ils.name, "Inline string marshalling failed");

            InlineArrayStruct ias = new InlineArrayStruct();
            ias.inlineArray = new short[128];

            for (short i = 0; i < 128; i++)
            {
                ias.inlineArray[i] = i;
            }

            ias.inlineString = "Hello";

            InlineUnicodeStruct ius = new InlineUnicodeStruct();
            ius.inlineString = "Hello World";

            ThrowIfNotEquals(true, InlineArrayTest(ref ias, ref ius), "inline array marshalling failed");
            bool pass = true;
            for (short i = 0; i < 128; i++)
            {
                if (ias.inlineArray[i] != i + 1)
                {
                    pass = false;
                }
            }
            ThrowIfNotEquals(true, pass, "inline array marshalling failed");

            ThrowIfNotEquals("Hello World", ias.inlineString, "Inline ByValTStr Ansi marshalling failed");

            ThrowIfNotEquals("Hello World", ius.inlineString, "Inline ByValTStr Unicode marshalling failed");

            pass = false;
            AutoStruct autoStruct = new AutoStruct();
            try
            {
                // passing struct with Auto layout should throw exception.
                StructTest_Auto(autoStruct);
            }
            catch (Exception)
            {
                pass = true;
            }
            ThrowIfNotEquals(true, pass, "Struct marshalling scenario6 failed.");

            Callbacks callbacks = new Callbacks();
            callbacks.callback0 = new Callback0(callbackFunc0);
            callbacks.callback1 = new Callback1(callbackFunc1);
            callbacks.callback2 = new Callback2(callbackFunc2);
            ThrowIfNotEquals(true,  RegisterCallbacks(ref callbacks), "Scenario 7: Struct with delegate marshalling failed");
        }

        private static void TestMarshalStructAPIs()
        {
            Console.WriteLine("Testing Marshal APIs for structs");

            NonBlittableStruct ts = new NonBlittableStruct() { f1 = 100, f2 = true, f3 = false, f4 = true };
            int size = Marshal.SizeOf<NonBlittableStruct>(ts);
            ThrowIfNotEquals(16, size, "Marshal.SizeOf<NonBlittableStruct> failed");
            IntPtr memory = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.StructureToPtr<NonBlittableStruct>(ts, memory, false);
                NonBlittableStruct ts2 = Marshal.PtrToStructure<NonBlittableStruct>(memory);
                ThrowIfNotEquals(true, ts2.f1 == 100 && ts2.f2 == true && ts2.f3 == false && ts2.f4 == true, "NonBlittableStruct marshalling Marshal API failed");

                IntPtr offset = Marshal.OffsetOf<NonBlittableStruct>("f2");
                ThrowIfNotEquals(new IntPtr(4), offset, "Struct marshalling OffsetOf failed.");
            }
            finally
            {
                Marshal.FreeHGlobal(memory);
            }

            BlittableClass bc = new BlittableClass() { f1 = 100, f2 = 12345678, f3 = 999, f4 = -4 };
            int bc_size = Marshal.SizeOf<BlittableClass>(bc);
            ThrowIfNotEquals(24, bc_size, "Marshal.SizeOf<BlittableClass> failed");
            IntPtr bc_memory = Marshal.AllocHGlobal(bc_size);
            try
            {
                Marshal.StructureToPtr<BlittableClass>(bc, bc_memory, false);
                BlittableClass bc2 = Marshal.PtrToStructure<BlittableClass>(bc_memory);
                ThrowIfNotEquals(true, bc2.f1 == 100 && bc2.f2 == 12345678 && bc2.f3 == 999 && bc2.f4 == -4, "BlittableClass marshalling Marshal API failed");
            }
            finally
            {
                Marshal.FreeHGlobal(bc_memory);
            }

            NonBlittableClass nbc = new NonBlittableClass() { f1 = false, f2 = true, f3 = 42 };
            int nbc_size = Marshal.SizeOf<NonBlittableClass>(nbc);
            ThrowIfNotEquals(12, nbc_size, "Marshal.SizeOf<NonBlittableClass> failed");
            IntPtr nbc_memory = Marshal.AllocHGlobal(nbc_size);
            try
            {
                Marshal.StructureToPtr<NonBlittableClass>(nbc, nbc_memory, false);
                NonBlittableClass nbc2 = Marshal.PtrToStructure<NonBlittableClass>(nbc_memory);
                ThrowIfNotEquals(true, nbc2.f1 == false && nbc2.f2 == true && nbc2.f3 == 42, "NonBlittableClass marshalling Marshal API failed");
            }
            finally
            {
                Marshal.FreeHGlobal(nbc_memory);
            }
        }
    }

    public class SafeMemoryHandle : SafeHandle //SafeHandle subclass
    {
        [DllImport("*", CallingConvention = CallingConvention.StdCall)]
        public static extern SafeMemoryHandle AllocateMemory(int size);

        [DllImport("*", CallingConvention = CallingConvention.StdCall)]
        public static extern bool ReleaseMemory(IntPtr handle);

        public SafeMemoryHandle()
            : base(IntPtr.Zero, true)
        {
        }

        private static readonly IntPtr _invalidHandleValue = new IntPtr(-1);

        public override bool IsInvalid
        {
            get { return handle == IntPtr.Zero || handle == _invalidHandleValue; }
        }

        override protected bool ReleaseHandle()
        {
            return ReleaseMemory(handle);
        }
    } //end of SafeMemoryHandle class

    public static class LowLevelExtensions
    {
        // Int32.ToString() calls into glob/loc garbage that hits CppCodegen limitations
        public static string LowLevelToString(this int i)
        {
            char[] digits = new char[11];
            int numDigits = 0;

            if (i == int.MinValue)
                return "-2147483648";

            bool negative = i < 0;
            if (negative)
                i = -i;

            do
            {
                digits[numDigits] = (char)('0' + (i % 10));
                numDigits++;
                i /= 10;
            }
            while (i != 0);
            if (negative)
            {
                digits[numDigits] = '-';
                numDigits++;
            }
            Array.Reverse(digits);
            return new string(digits, digits.Length - numDigits, numDigits);
        }
    }
}