summaryrefslogtreecommitdiff
path: root/tests/src/GC/API/GCHandle/AddrOfPinnedObject_neg.cs
blob: 9af56b6aced6af9d7c65d126a1756a91306d516b (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
// 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.

// Negative Test for GCHandle.AddrOfPinnedObject()...should throw and exception when handle is not pinned.

using System;
using System.Runtime.InteropServices;

public class Test
{
    public static int Main()
    {
        int[] array = new int[25];
        bool passed = true;

        Console.WriteLine("Allocating a normal handle to object..");
        GCHandle handle = GCHandle.Alloc(array);  // handle is NOT pinned.

        try
        {
            IntPtr addr = handle.AddrOfPinnedObject();
            Console.WriteLine("AddrOfPinnedObject = {0}", addr);
        }
        catch (InvalidOperationException)
        {
            Console.WriteLine("Caught expected exception");
        }
        catch (Exception)
        {
            Console.WriteLine("Caught unexpected exception!");
            Console.WriteLine("Test1 Failed!");
            passed = false;
        }

        handle.Free();

        try
        {
            IntPtr addr = handle.AddrOfPinnedObject();
            Console.WriteLine("AddrOfPinnedObject = {0}", addr);
        }
        catch (InvalidOperationException)
        {
            Console.WriteLine("Caught expected exception");
        }
        catch (Exception)
        {
            Console.WriteLine("Caught unexpected exception!");
            Console.WriteLine("Test1 Failed!");
            passed = false;
        }


        if (!passed)
        {
            Console.WriteLine("Test Failed!");
            return 1;
        }

        Console.WriteLine("Test Passed!");
        return 100;
    }
}