Port CustomMarshalers.dll to C# and .NET Core (#21343)
[platform/upstream/coreclr.git] / src / System.Private.CoreLib / src / System / Runtime / InteropServices / CustomMarshalers / EnumerableToDispatchMarshaler.cs
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.
4
5 using System.Collections;
6
7 namespace System.Runtime.InteropServices.CustomMarshalers
8 {
9     internal class EnumerableToDispatchMarshaler : ICustomMarshaler
10     {
11         private static readonly EnumerableToDispatchMarshaler s_enumerableToDispatchMarshaler = new EnumerableToDispatchMarshaler();
12
13         public static ICustomMarshaler GetInstance(string cookie) => s_enumerableToDispatchMarshaler;
14
15         private EnumerableToDispatchMarshaler()
16         {
17         }
18
19         public void CleanUpManagedData(object ManagedObj)
20         {
21         }
22
23         public void CleanUpNativeData(IntPtr pNativeData)
24         {
25             Marshal.Release(pNativeData);
26         }
27
28         public int GetNativeDataSize()
29         {
30             // Return -1 to indicate the managed type this marshaler handles is not a value type.
31             return -1;
32         }
33
34         public IntPtr MarshalManagedToNative(object ManagedObj)
35         {
36             if (ManagedObj == null)
37             {
38                 throw new ArgumentNullException(nameof(ManagedObj));
39             }
40
41             return Marshal.GetComInterfaceForObject<object, IEnumerable>(ManagedObj);
42         }
43
44         public object MarshalNativeToManaged(IntPtr pNativeData)
45         {
46             if (pNativeData == IntPtr.Zero)
47             {
48                 throw new ArgumentNullException(nameof(pNativeData));
49             }
50
51             object comObject = Marshal.GetObjectForIUnknown(pNativeData);
52
53             return ComDataHelpers.GetOrCreateManagedViewFromComData<object, EnumerableViewOfDispatch>(comObject, obj => new EnumerableViewOfDispatch(obj));
54         }
55     }
56 }