Skip to content

Code Quality: Introduced ComPtr #16152

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 9, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions src/Files.App.CsWin32/Windows.Win32.ComPtr.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// 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 COM pointer and a set of methods to work with the pointer safely.
/// </summary>
public unsafe struct ComPtr<T> : IDisposable where T : unmanaged
{
private T* _ptr;

public bool IsNull
=> _ptr == default;

public ComPtr(T* ptr)
{
_ptr = ptr;

if (ptr is not null)
((IUnknown*)ptr)->AddRef();
}

[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;
((IUnknown*)ptr)->Release();
}
}
}
}