diff --git a/src/ComputeSharp.D2D1.Uwp/Extensions/IUnknownExtensions.cs b/src/ComputeSharp.D2D1.Uwp/Extensions/IUnknownExtensions.cs index 11610412..f3847d30 100644 --- a/src/ComputeSharp.D2D1.Uwp/Extensions/IUnknownExtensions.cs +++ b/src/ComputeSharp.D2D1.Uwp/Extensions/IUnknownExtensions.cs @@ -47,11 +47,18 @@ internal static unsafe class IUnknownExtensions /// The type of object being copied. /// The source object. /// The destination location. - public static void CopyTo(this ref T source, ref ComPtr destination) + /// The for the operation (always ). + public static HRESULT CopyTo(this ref T source, ref ComPtr destination) where T : unmanaged // IUnknown { - destination.Dispose(); + // 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)); - destination = new ComPtr((T*)Unsafe.AsPointer(ref source)); + return temporary.CopyTo(ref destination); } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs index 8e3ab29e..61688e34 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs @@ -116,7 +116,7 @@ unsafe partial class PixelShaderEffect // Store the input realization device and canvas device for future uses d2D1Device1.CopyTo(ref this.d2D1RealizationDevice).Assert(); - device->CopyTo(ref this.canvasDevice); + device->CopyTo(ref this.canvasDevice).Assert(); } // Create the effect, if it doesn't exist already