Skip to content

Commit 0aea31f

Browse files
authored
Code Quality: Introduced ComPtr for unmanaged COM pointers (#16152)
1 parent a1a9f27 commit 0aea31f

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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 COM pointer and a set of methods to work with the pointer safely.
13+
/// </summary>
14+
public unsafe struct ComPtr<T> : IDisposable where T : unmanaged
15+
{
16+
private T* _ptr;
17+
18+
public bool IsNull
19+
=> _ptr == default;
20+
21+
public ComPtr(T* ptr)
22+
{
23+
_ptr = ptr;
24+
25+
if (ptr is not null)
26+
((IUnknown*)ptr)->AddRef();
27+
}
28+
29+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
30+
public readonly T* Get()
31+
{
32+
return _ptr;
33+
}
34+
35+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
36+
public readonly T** GetAddressOf()
37+
{
38+
return (T**)Unsafe.AsPointer(ref Unsafe.AsRef(in this));
39+
}
40+
41+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
42+
public void Dispose()
43+
{
44+
T* ptr = _ptr;
45+
if (ptr is not null)
46+
{
47+
_ptr = null;
48+
((IUnknown*)ptr)->Release();
49+
}
50+
}
51+
}
52+
}

0 commit comments

Comments
 (0)