using System.Runtime.CompilerServices; using ComputeSharp.D2D1.Extensions; using ComputeSharp.Win32; namespace ComputeSharp.D2D1.WinUI.Extensions; /// /// Helper methods for working with the type. /// internal static unsafe class IUnknownExtensions { /// /// Checks whether two values have the same underlying COM object. /// /// The type of the first value to check. /// The type of the second value to check. /// The first object to compare. /// The second object to compare. /// Whether and point to the same COM object. public static bool IsSameInstance(this ref T left, U* right) where T : unmanaged // IUnknown where U : unmanaged // IUnknown { if (Unsafe.AreSame(ref left, ref *(T*)right)) { return true; } if (Unsafe.IsNullRef(ref left) || right is null) { return false; } using ComPtr leftUnknown = default; using ComPtr rightUnknown = default; ((IUnknown*)Unsafe.AsPointer(ref left))->QueryInterface(Win32.Windows.__uuidof(), (void**)leftUnknown.GetAddressOf()).Assert(); ((IUnknown*)right)->QueryInterface(Win32.Windows.__uuidof(), (void**)rightUnknown.GetAddressOf()).Assert(); return leftUnknown.Get() == rightUnknown.Get(); } /// /// Copies the source object onto a target destination. /// /// The type of object being copied. /// The source object. /// The destination location. /// The for the operation. public static HRESULT CopyTo(this ref T source, ref ComPtr destination) where T : unmanaged // IUnknown { // Note: this explicitly needs a temporary copy to avoid issues in case source and destination were // pointers to the same object (which can be the case even if the two pointers are not identical). // To double check, a full check through an IUnknown* cast would be needed, but to avoid the extra // QueryInterface call on both objects, we can just always do one AddRef call which avoids issues in // all cases as well. The situation we need to avoid is that without a temporary copy, releasing the // target object might actually destroy the object, causing the following AddRef call to AV. using ComPtr temporary = new((T*)Unsafe.AsPointer(ref source)); return temporary.CopyTo(ref destination); } /// /// Copies the source object onto a target location. /// /// The type of object being copied. /// The type of destination object being copied. /// The source object. /// The destination location. /// The for the operation. public static HRESULT CopyTo(this ref T source, U** destination) where T : unmanaged // IUnknown where U : unmanaged, IComObject { using ComPtr temporary = new((T*)Unsafe.AsPointer(ref source)); return temporary.CopyTo(destination); } }