diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumerableViewOfDispatch.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumerableViewOfDispatch.cs index d67948660a3a9..339c43980aff9 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumerableViewOfDispatch.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumerableViewOfDispatch.cs @@ -40,13 +40,25 @@ public IEnumerator GetEnumerator() IntPtr.Zero); } - object? resultAsObject = result.ToObject(); - if (!(resultAsObject is IEnumVARIANT enumVariant)) + IntPtr enumVariantPtr = IntPtr.Zero; + try { - throw new InvalidOperationException(SR.InvalidOp_InvalidNewEnumVariant); + object? resultAsObject = result.ToObject(); + if (!(resultAsObject is IEnumVARIANT enumVariant)) + { + throw new InvalidOperationException(SR.InvalidOp_InvalidNewEnumVariant); + } + + enumVariantPtr = Marshal.GetIUnknownForObject(enumVariant); + return (IEnumerator)EnumeratorToEnumVariantMarshaler.GetInstance(null).MarshalNativeToManaged(enumVariantPtr); } + finally + { + result.Clear(); - return (IEnumerator)EnumeratorToEnumVariantMarshaler.GetInstance(null).MarshalNativeToManaged(Marshal.GetIUnknownForObject(enumVariant)); + if (enumVariantPtr != IntPtr.Zero) + Marshal.Release(enumVariantPtr); + } } public object GetUnderlyingObject()