1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
6 using System.Collections;
7 using System.Runtime.InteropServices.ComTypes;
9 namespace System.Runtime.InteropServices.CustomMarshalers
11 internal class EnumeratorToEnumVariantMarshaler : ICustomMarshaler
13 private static readonly EnumeratorToEnumVariantMarshaler s_enumeratorToEnumVariantMarshaler = new EnumeratorToEnumVariantMarshaler();
15 public static ICustomMarshaler GetInstance(string? cookie) => s_enumeratorToEnumVariantMarshaler;
17 private EnumeratorToEnumVariantMarshaler()
21 public void CleanUpManagedData(object ManagedObj)
25 public void CleanUpNativeData(IntPtr pNativeData)
27 Marshal.Release(pNativeData);
30 public int GetNativeDataSize()
32 // Return -1 to indicate the managed type this marshaler handles is not a value type.
36 public IntPtr MarshalManagedToNative(object ManagedObj)
38 if (ManagedObj == null)
40 throw new ArgumentNullException(nameof(ManagedObj));
43 if (ManagedObj is EnumeratorViewOfEnumVariant view)
45 return Marshal.GetComInterfaceForObject<object, IEnumVARIANT>(view.GetUnderlyingObject());
48 EnumVariantViewOfEnumerator nativeView = new EnumVariantViewOfEnumerator((IEnumerator)ManagedObj);
50 return Marshal.GetComInterfaceForObject<EnumVariantViewOfEnumerator, IEnumVARIANT>(nativeView);
53 public object MarshalNativeToManaged(IntPtr pNativeData)
55 if (pNativeData == IntPtr.Zero)
57 throw new ArgumentNullException(nameof(pNativeData));
60 object comObject = Marshal.GetObjectForIUnknown(pNativeData);
62 if (!comObject.GetType().IsCOMObject)
64 if (comObject is EnumVariantViewOfEnumerator enumVariantView)
66 return enumVariantView.Enumerator;
69 return (comObject as IEnumerator)!;
72 return ComDataHelpers.GetOrCreateManagedViewFromComData<IEnumVARIANT, EnumeratorViewOfEnumVariant>(comObject, var => new EnumeratorViewOfEnumVariant(var));