Skip to content

Commit 0debeee

Browse files
authored
Code Quality: Introduced ComHeapPtr (#16237)
1 parent b454edf commit 0debeee

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

src/Files.App.CsWin32/NativeMethods.txt

+1
Original file line numberDiff line numberDiff line change
@@ -133,4 +133,5 @@ IFileOperation
133133
IShellItem2
134134
PSGetPropertyKeyFromName
135135
ShellExecuteEx
136+
CoTaskMemFree
136137
QueryDosDevice
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// Copyright (c) 2024 Files Community
2+
// Licensed under the MIT License. See the LICENSE.
3+
4+
using System;
5+
using System.Runtime.CompilerServices;
6+
using Windows.Win32;
7+
using Windows.Win32.System.Com;
8+
9+
namespace Windows.Win32
10+
{
11+
/// <summary>
12+
/// Contains a heap pointer allocated via CoTaskMemAlloc and a set of methods to work with the pointer safely.
13+
/// </summary>
14+
public unsafe struct ComHeapPtr<T> : IDisposable where T : unmanaged
15+
{
16+
private T* _ptr;
17+
18+
public bool IsNull
19+
=> _ptr == default;
20+
21+
public ComHeapPtr(T* ptr)
22+
{
23+
_ptr = ptr;
24+
}
25+
26+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
27+
public readonly T* Get()
28+
{
29+
return _ptr;
30+
}
31+
32+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
33+
public readonly T** GetAddressOf()
34+
{
35+
return (T**)Unsafe.AsPointer(ref Unsafe.AsRef(in this));
36+
}
37+
38+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
39+
public void Dispose()
40+
{
41+
T* ptr = _ptr;
42+
if (ptr is not null)
43+
{
44+
_ptr = null;
45+
PInvoke.CoTaskMemFree((void*)ptr);
46+
}
47+
}
48+
}
49+
}

0 commit comments

Comments
 (0)