#if NETCOREAPP || NETSTANDARD2_0
using System.Collections;
using System.Runtime.InteropServices.ComTypes;
using Vanara.PInvoke;
namespace System.Runtime.InteropServices.CustomMarshalers
{
/// Marshals the COM IEnumVARIANT interface to the .NET Framework interface, and vice versa.
///
/// This custom marshaler marshals IEnumVARIANT to and marshals to
/// IEnumVARIANT. The CLR automatically uses this class to bridge COM enumerators and .NET enumerators. The type returned by the GetEnumerator method in the imported COM class uses EnumeratorToEnumVariantMarshaler
/// to map the calls to the IEnumVARIANT interface pointer returned by the COM object's member with a DISPID of -4.
///
public class EnumeratorToEnumVariantMarshaler : ICustomMarshaler
{
private static readonly EnumeratorToEnumVariantMarshaler s_enumeratorToEnumVariantMarshaler = new();
/// Returns an instance of the custom marshaler.
/// String "cookie" parameter that can be used by the custom marshaler.
/// An instance of the custom marshaler.
public static ICustomMarshaler GetInstance(string cookie) => s_enumeratorToEnumVariantMarshaler;
private EnumeratorToEnumVariantMarshaler()
{
}
/// Performs necessary cleanup of the managed data when it is no longer needed.
/// The managed object to be destroyed.
public void CleanUpManagedData(object ManagedObj)
{
}
/// Performs necessary cleanup of the unmanaged data when it is no longer needed.
/// A pointer to the unmanaged data to be destroyed.
public void CleanUpNativeData(IntPtr pNativeData) => Marshal.Release(pNativeData);
/// Returns the size in bytes of the unmanaged data to be marshaled.
/// -1 to indicate the type this marshaler handles is not a value type.
public int GetNativeDataSize() =>
// Return -1 to indicate the managed type this marshaler handles is not a value type.
-1;
/// Marshals an object from managed code to unmanaged code.
/// The managed object to be converted.
/// A pointer to the unmanaged object.
public IntPtr MarshalManagedToNative(object ManagedObj)
{
if (ManagedObj == null)
{
throw new ArgumentNullException(nameof(ManagedObj));
}
if (ManagedObj is EnumeratorViewOfEnumVariant view)
{
return Marshal.GetComInterfaceForObject