Skip to content

Commit

Permalink
Code Quality: Introduced ComHeapPtr (#16237)
Browse files Browse the repository at this point in the history
  • Loading branch information
0x5bfa authored Sep 30, 2024
1 parent b454edf commit 0debeee
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/Files.App.CsWin32/NativeMethods.txt
Original file line number Diff line number Diff line change
Expand Up @@ -133,4 +133,5 @@ IFileOperation
IShellItem2
PSGetPropertyKeyFromName
ShellExecuteEx
CoTaskMemFree
QueryDosDevice
49 changes: 49 additions & 0 deletions src/Files.App.CsWin32/Windows.Win32.ComHeapPtr.cs
Original file line number Diff line number Diff line change
@@ -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
{
/// <summary>
/// Contains a heap pointer allocated via CoTaskMemAlloc and a set of methods to work with the pointer safely.
/// </summary>
public unsafe struct ComHeapPtr<T> : 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);
}
}
}
}

0 comments on commit 0debeee

Please sign in to comment.