More Corelib cleanup (dotnet/coreclr#26872)
[mono-project.git] / netcore / System.Private.CoreLib / shared / System / Buffers / MemoryHandle.cs
blobf1da6d273ea49f7a67dbf9395768d1094a77e497
1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
5 using System.Runtime.InteropServices;
7 namespace System.Buffers
9 /// <summary>
10 /// A handle for the memory.
11 /// </summary>
12 public unsafe struct MemoryHandle : IDisposable
14 private void* _pointer;
15 private GCHandle _handle;
16 private IPinnable? _pinnable;
18 /// <summary>
19 /// Creates a new memory handle for the memory.
20 /// </summary>
21 /// <param name="pointer">pointer to memory</param>
22 /// <param name="pinnable">reference to manually managed object, or default if there is no memory manager</param>
23 /// <param name="handle">handle used to pin array buffers</param>
24 [CLSCompliant(false)]
25 public MemoryHandle(void* pointer, GCHandle handle = default, IPinnable? pinnable = default)
27 _pointer = pointer;
28 _handle = handle;
29 _pinnable = pinnable;
32 /// <summary>
33 /// Returns the pointer to memory, where the memory is assumed to be pinned and hence the address won't change.
34 /// </summary>
35 [CLSCompliant(false)]
36 public void* Pointer => _pointer;
38 /// <summary>
39 /// Frees the pinned handle and releases IPinnable.
40 /// </summary>
41 public void Dispose()
43 if (_handle.IsAllocated)
45 _handle.Free();
48 if (_pinnable != null)
50 _pinnable.Unpin();
51 _pinnable = null;
54 _pointer = null;