| | | 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 | | |
| | | 4 | | using System.Runtime.InteropServices; |
| | | 5 | | |
| | | 6 | | namespace System.Buffers |
| | | 7 | | { |
| | | 8 | | /// <summary> |
| | | 9 | | /// A handle for the memory. |
| | | 10 | | /// </summary> |
| | | 11 | | public unsafe struct MemoryHandle : IDisposable |
| | | 12 | | { |
| | | 13 | | private void* _pointer; |
| | | 14 | | private GCHandle _handle; |
| | | 15 | | private IPinnable? _pinnable; |
| | | 16 | | |
| | | 17 | | /// <summary> |
| | | 18 | | /// Creates a new memory handle for the memory. |
| | | 19 | | /// </summary> |
| | | 20 | | /// <param name="pointer">pointer to memory</param> |
| | | 21 | | /// <param name="pinnable">reference to manually managed object, or default if there is no memory manager</param |
| | | 22 | | /// <param name="handle">handle used to pin array buffers</param> |
| | | 23 | | /// <safety>Only stores the supplied pointer, GC handle, and pinnable reference into the struct's fields; it per |
| | | 24 | | [CLSCompliant(false)] |
| | | 25 | | public MemoryHandle(void* pointer, GCHandle handle = default, IPinnable? pinnable = default) |
| | | 26 | | { |
| | 0 | 27 | | _pointer = pointer; |
| | 0 | 28 | | _handle = handle; |
| | 0 | 29 | | _pinnable = pinnable; |
| | 0 | 30 | | } |
| | | 31 | | |
| | | 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 | | /// <safety>Returns the stored pointer value to already-pinned memory; obtaining the address performs no derefer |
| | | 36 | | [CLSCompliant(false)] |
| | 0 | 37 | | public void* Pointer => _pointer; |
| | | 38 | | |
| | | 39 | | /// <summary> |
| | | 40 | | /// Frees the pinned handle and releases IPinnable. |
| | | 41 | | /// </summary> |
| | | 42 | | public void Dispose() |
| | | 43 | | { |
| | 0 | 44 | | if (_handle.IsAllocated) |
| | | 45 | | { |
| | 0 | 46 | | _handle.Free(); |
| | | 47 | | } |
| | | 48 | | |
| | 0 | 49 | | if (_pinnable != null) |
| | | 50 | | { |
| | 0 | 51 | | _pinnable.Unpin(); |
| | 0 | 52 | | _pinnable = null; |
| | | 53 | | } |
| | | 54 | | |
| | 0 | 55 | | _pointer = null; |
| | 0 | 56 | | } |
| | | 57 | | } |
| | | 58 | | } |
| | | 59 | | |