|
| 1 | +// Copyright (c) Files Community |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Runtime.CompilerServices; |
| 6 | +using System.Runtime.InteropServices; |
| 7 | + |
| 8 | +namespace Windows.Win32 |
| 9 | +{ |
| 10 | + /// <summary> |
| 11 | + /// Contains a heap pointer allocated via <see cref="NativeMemory.Alloc"/> and a set of methods to work with the pointer safely. |
| 12 | + /// </summary> |
| 13 | + public unsafe struct HeapPtr<T> : IDisposable where T : unmanaged |
| 14 | + { |
| 15 | + private T* _ptr; |
| 16 | + |
| 17 | + public readonly bool IsNull |
| 18 | + { |
| 19 | + [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| 20 | + get => _ptr is null; |
| 21 | + } |
| 22 | + |
| 23 | + public HeapPtr(T* ptr) |
| 24 | + { |
| 25 | + _ptr = ptr; |
| 26 | + } |
| 27 | + |
| 28 | + [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| 29 | + public readonly T* Get() |
| 30 | + { |
| 31 | + return _ptr; |
| 32 | + } |
| 33 | + |
| 34 | + [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| 35 | + public readonly T** GetAddressOf() |
| 36 | + { |
| 37 | + return (T**)Unsafe.AsPointer(ref Unsafe.AsRef(in this)); |
| 38 | + } |
| 39 | + |
| 40 | + [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| 41 | + public void Attach(T* ptr) |
| 42 | + { |
| 43 | + Dispose(); |
| 44 | + _ptr = ptr; |
| 45 | + } |
| 46 | + |
| 47 | + [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| 48 | + public T* Detach() |
| 49 | + { |
| 50 | + T* ptr = _ptr; |
| 51 | + _ptr = null; |
| 52 | + return ptr; |
| 53 | + } |
| 54 | + |
| 55 | + [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| 56 | + public bool Allocate(nuint cch) |
| 57 | + { |
| 58 | + _ptr = (T*)NativeMemory.Alloc(cch); // malloc() |
| 59 | + return _ptr is not null; |
| 60 | + } |
| 61 | + |
| 62 | + [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| 63 | + public bool Reallocate(nuint cch) |
| 64 | + { |
| 65 | + T* ptr = (T*)PInvoke.CoTaskMemRealloc(_ptr, cch); |
| 66 | + if (ptr is null) return false; |
| 67 | + _ptr = ptr; |
| 68 | + return true; |
| 69 | + } |
| 70 | + |
| 71 | + [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| 72 | + public void Dispose() |
| 73 | + { |
| 74 | + T* ptr = _ptr; |
| 75 | + if (ptr is null) return; |
| 76 | + _ptr = null; |
| 77 | + NativeMemory.Free(ptr); // free() |
| 78 | + } |
| 79 | + } |
| 80 | +} |
0 commit comments