From 0debeee681f3443808ca49d47dc3e829c8a5e795 Mon Sep 17 00:00:00 2001 From: 0x5BFA <62196528+0x5bfa@users.noreply.github.com> Date: Tue, 1 Oct 2024 01:56:17 +0900 Subject: [PATCH] Code Quality: Introduced ComHeapPtr (#16237) --- src/Files.App.CsWin32/NativeMethods.txt | 1 + .../Windows.Win32.ComHeapPtr.cs | 49 +++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 src/Files.App.CsWin32/Windows.Win32.ComHeapPtr.cs 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); + } + } + } +}