-
Notifications
You must be signed in to change notification settings - Fork 2
/
LP_Pinner.cs
62 lines (57 loc) · 1.71 KB
/
LP_Pinner.cs
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
using System;
using System.Runtime.InteropServices;
namespace TrayIconBuster
{
/// <summary>
/// An LP_Pinner object pins an object for as long as the LP_Pinner object is alive.
/// </summary>
/// <remarks>
/// This is the preferred use when the pointer value is not needed:
/// using (new LP_Pinner(objectThatNeedsPinning)) {
/// .. use the object here, it is pinned now ...
/// }
/// This is the preferred use when the pointer value is needed:
/// using (LP_Pinner pinning=new LP_Pinner(objectThatNeedsPinning)) {
/// IntPtr ptr=pinning.Ptr;
/// .. use the object here, it is pinned now ...
/// }
/// </remarks>
public class LP_Pinner : IDisposable
{
private GCHandle handle;
private bool disposed;
private IntPtr ptr;
/// <summary>
/// Creates an instance op LP_Pinner, and pins the argument.
/// </summary>
/// <param name="obj"></param>
public LP_Pinner(object obj)
{
handle = GCHandle.Alloc(obj, GCHandleType.Pinned);
ptr = handle.AddrOfPinnedObject();
}
/// <summary>
/// Undoes the pinning.
/// </summary>
~LP_Pinner()
{
Dispose();
}
/// <summary>
/// Disposes of the object's internal resources.
/// </summary>
public void Dispose()
{
if (!disposed)
{
disposed = true;
handle.Free();
ptr = IntPtr.Zero;
}
}
/// <summary>
/// Returns the pointer to the pinned object.
/// </summary>
public IntPtr Ptr { get { return ptr; } }
}
}