diff --git a/src/Files.App.CsWin32/NativeMethods.txt b/src/Files.App.CsWin32/NativeMethods.txt index 88a2a6a276d4..ecb7005f7a87 100644 --- a/src/Files.App.CsWin32/NativeMethods.txt +++ b/src/Files.App.CsWin32/NativeMethods.txt @@ -133,4 +133,5 @@ IFileOperation IShellItem2 PSGetPropertyKeyFromName ShellExecuteEx +CoTaskMemFree QueryDosDevice diff --git a/src/Files.App.CsWin32/Windows.Win32.ComHeapPtr.cs b/src/Files.App.CsWin32/Windows.Win32.ComHeapPtr.cs new file mode 100644 index 000000000000..14f248ee7ff5 --- /dev/null +++ b/src/Files.App.CsWin32/Windows.Win32.ComHeapPtr.cs @@ -0,0 +1,49 @@ +// Copyright (c) 2024 Files Community +// Licensed under the MIT License. See the LICENSE. + +using System; +using System.Runtime.CompilerServices; +using Windows.Win32; +using Windows.Win32.System.Com; + +namespace Windows.Win32 +{ + /// + /// Contains a heap pointer allocated via CoTaskMemAlloc and a set of methods to work with the pointer safely. + /// + public unsafe struct ComHeapPtr : IDisposable where T : unmanaged + { + private T* _ptr; + + public bool IsNull + => _ptr == default; + + public ComHeapPtr(T* ptr) + { + _ptr = ptr; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly T* Get() + { + return _ptr; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly T** GetAddressOf() + { + return (T**)Unsafe.AsPointer(ref Unsafe.AsRef(in this)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + T* ptr = _ptr; + if (ptr is not null) + { + _ptr = null; + PInvoke.CoTaskMemFree((void*)ptr); + } + } + } +}