/
MemoryHandle.cs
56 lines (49 loc) · 1.66 KB
/
MemoryHandle.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.InteropServices;
namespace System.Buffers
{
/// <summary>
/// A handle for the memory.
/// </summary>
public unsafe struct MemoryHandle : IDisposable
{
private void* _pointer;
private GCHandle _handle;
private IPinnable? _pinnable;
/// <summary>
/// Creates a new memory handle for the memory.
/// </summary>
/// <param name="pointer">pointer to memory</param>
/// <param name="pinnable">reference to manually managed object, or default if there is no memory manager</param>
/// <param name="handle">handle used to pin array buffers</param>
[CLSCompliant(false)]
public MemoryHandle(void* pointer, GCHandle handle = default, IPinnable? pinnable = default)
{
_pointer = pointer;
_handle = handle;
_pinnable = pinnable;
}
/// <summary>
/// Returns the pointer to memory, where the memory is assumed to be pinned and hence the address won't change.
/// </summary>
[CLSCompliant(false)]
public void* Pointer => _pointer;
/// <summary>
/// Frees the pinned handle and releases IPinnable.
/// </summary>
public void Dispose()
{
if (_handle.IsAllocated)
{
_handle.Free();
}
if (_pinnable != null)
{
_pinnable.Unpin();
_pinnable = null;
}
_pointer = null;
}
}
}