/
Marshal.CoreCLR.cs
996 lines (821 loc) · 41.4 KB
/
Marshal.CoreCLR.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices.ComTypes;
using System.Runtime.Versioning;
using System.StubHelpers;
namespace System.Runtime.InteropServices
{
/// <summary>
/// This class contains methods that are mainly used to marshal between unmanaged
/// and managed types.
/// </summary>
public static partial class Marshal
{
#if FEATURE_COMINTEROP
/// <summary>
/// IUnknown is {00000000-0000-0000-C000-000000000046}
/// </summary>
internal static Guid IID_IUnknown = new Guid(0, 0, 0, 0xC0, 0, 0, 0, 0, 0, 0, 0x46);
#endif //FEATURE_COMINTEROP
internal static int SizeOfHelper(RuntimeType t, [MarshalAs(UnmanagedType.Bool)] bool throwIfNotMarshalable)
=> SizeOfHelper(new QCallTypeHandle(ref t), throwIfNotMarshalable);
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_SizeOfHelper")]
private static partial int SizeOfHelper(QCallTypeHandle t, [MarshalAs(UnmanagedType.Bool)] bool throwIfNotMarshalable);
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern",
Justification = "Trimming doesn't affect types eligible for marshalling. Different exception for invalid inputs doesn't matter.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public static IntPtr OffsetOf(Type t, string fieldName)
{
ArgumentNullException.ThrowIfNull(t);
FieldInfo? f = t.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (f is null)
{
throw new ArgumentException(SR.Format(SR.Argument_OffsetOfFieldNotFound, t.FullName), nameof(fieldName));
}
if (!(f is RtFieldInfo rtField))
{
throw new ArgumentException(SR.Argument_MustBeRuntimeFieldInfo, nameof(fieldName));
}
nint offset = OffsetOf(rtField.GetFieldHandle());
GC.KeepAlive(rtField);
return offset;
}
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_OffsetOf")]
private static partial nint OffsetOf(IntPtr pFD);
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("ReadByte(Object, Int32) may be unavailable in future releases.")]
[RequiresDynamicCode("Marshalling code for the object might not be available")]
public static byte ReadByte(object ptr, int ofs)
{
return ReadValueSlow(ptr, ofs, ReadByte);
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("ReadInt16(Object, Int32) may be unavailable in future releases.")]
[RequiresDynamicCode("Marshalling code for the object might not be available")]
public static short ReadInt16(object ptr, int ofs)
{
return ReadValueSlow(ptr, ofs, ReadInt16);
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("ReadInt32(Object, Int32) may be unavailable in future releases.")]
[RequiresDynamicCode("Marshalling code for the object might not be available")]
public static int ReadInt32(object ptr, int ofs)
{
return ReadValueSlow(ptr, ofs, ReadInt32);
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("ReadInt64(Object, Int32) may be unavailable in future releases.")]
[RequiresDynamicCode("Marshalling code for the object might not be available")]
#pragma warning disable CS0618 // Type or member is obsolete
public static long ReadInt64([MarshalAs(UnmanagedType.AsAny), In] object ptr, int ofs)
#pragma warning restore CS0618 // Type or member is obsolete
{
return ReadValueSlow(ptr, ofs, ReadInt64);
}
/// <summary>Read value from marshaled object (marshaled using AsAny).</summary>
/// <remarks>
/// It's quite slow and can return back dangling pointers. It's only there for backcompat.
/// People should instead use the IntPtr overloads.
/// </remarks>
private static unsafe T ReadValueSlow<T>(object ptr, int ofs, Func<IntPtr, int, T> readValueHelper)
{
// Consumers of this method are documented to throw AccessViolationException on any AV
if (ptr is null)
{
throw new AccessViolationException();
}
const int Flags =
(int)AsAnyMarshaler.AsAnyFlags.In |
(int)AsAnyMarshaler.AsAnyFlags.IsAnsi |
(int)AsAnyMarshaler.AsAnyFlags.IsBestFit;
MngdNativeArrayMarshaler.MarshalerState nativeArrayMarshalerState = default;
AsAnyMarshaler marshaler = new AsAnyMarshaler(new IntPtr(&nativeArrayMarshalerState));
IntPtr pNativeHome = IntPtr.Zero;
try
{
pNativeHome = marshaler.ConvertToNative(ptr, Flags);
return readValueHelper(pNativeHome, ofs);
}
finally
{
marshaler.ClearNative(pNativeHome);
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("WriteByte(Object, Int32, Byte) may be unavailable in future releases.")]
[RequiresDynamicCode("Marshalling code for the object might not be available")]
public static void WriteByte(object ptr, int ofs, byte val)
{
WriteValueSlow(ptr, ofs, val, WriteByte);
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("WriteInt16(Object, Int32, Int16) may be unavailable in future releases.")]
[RequiresDynamicCode("Marshalling code for the object might not be available")]
public static void WriteInt16(object ptr, int ofs, short val)
{
WriteValueSlow(ptr, ofs, val, WriteInt16);
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("WriteInt32(Object, Int32, Int32) may be unavailable in future releases.")]
[RequiresDynamicCode("Marshalling code for the object might not be available")]
public static void WriteInt32(object ptr, int ofs, int val)
{
WriteValueSlow(ptr, ofs, val, WriteInt32);
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("WriteInt64(Object, Int32, Int64) may be unavailable in future releases.")]
[RequiresDynamicCode("Marshalling code for the object might not be available")]
public static void WriteInt64(object ptr, int ofs, long val)
{
WriteValueSlow(ptr, ofs, val, WriteInt64);
}
/// <summary>
/// Write value into marshaled object (marshaled using AsAny) and propagate the
/// value back. This is quite slow and can return back dangling pointers. It is
/// only here for backcompat. People should instead use the IntPtr overloads.
/// </summary>
private static unsafe void WriteValueSlow<T>(object ptr, int ofs, T val, Action<IntPtr, int, T> writeValueHelper)
{
// Consumers of this method are documented to throw AccessViolationException on any AV
if (ptr is null)
{
throw new AccessViolationException();
}
const int Flags =
(int)AsAnyMarshaler.AsAnyFlags.In |
(int)AsAnyMarshaler.AsAnyFlags.Out |
(int)AsAnyMarshaler.AsAnyFlags.IsAnsi |
(int)AsAnyMarshaler.AsAnyFlags.IsBestFit;
MngdNativeArrayMarshaler.MarshalerState nativeArrayMarshalerState = default;
AsAnyMarshaler marshaler = new AsAnyMarshaler(new IntPtr(&nativeArrayMarshalerState));
IntPtr pNativeHome = IntPtr.Zero;
try
{
pNativeHome = marshaler.ConvertToNative(ptr, Flags);
writeValueHelper(pNativeHome, ofs, val);
marshaler.ConvertToManaged(ptr, pNativeHome);
}
finally
{
marshaler.ClearNative(pNativeHome);
}
}
/// <summary>
/// Get the last platform invoke error on the current thread
/// </summary>
/// <returns>The last platform invoke error</returns>
/// <remarks>
/// The last platform invoke error corresponds to the error set by either the most recent platform
/// invoke that was configured to set the last error or a call to <see cref="SetLastPInvokeError(int)" />.
/// </remarks>
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern int GetLastPInvokeError();
/// <summary>
/// Set the last platform invoke error on the current thread
/// </summary>
/// <param name="error">Error to set</param>
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void SetLastPInvokeError(int error);
private static void PrelinkCore(MethodInfo m)
{
if (!(m is RuntimeMethodInfo rmi))
{
throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(m));
}
InternalPrelink(((IRuntimeMethodInfo)rmi).Value);
GC.KeepAlive(rmi);
}
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_Prelink")]
private static partial void InternalPrelink(RuntimeMethodHandleInternal m);
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern /* struct _EXCEPTION_POINTERS* */ IntPtr GetExceptionPointers();
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("GetExceptionCode() may be unavailable in future releases.")]
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern int GetExceptionCode();
/// <summary>
/// Marshals data from a structure class to a native memory block. If the
/// structure contains pointers to allocated blocks and "fDeleteOld" is
/// true, this routine will call DestroyStructure() first.
/// </summary>
[RequiresDynamicCode("Marshalling code for the object might not be available. Use the StructureToPtr<T> overload instead.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public static unsafe void StructureToPtr(object structure, IntPtr ptr, bool fDeleteOld)
{
ArgumentNullException.ThrowIfNull(ptr);
ArgumentNullException.ThrowIfNull(structure);
MethodTable* pMT = RuntimeHelpers.GetMethodTable(structure);
if (pMT->HasInstantiation)
throw new ArgumentException(SR.Argument_NeedNonGenericObject, nameof(structure));
delegate*<ref byte, byte*, int, ref CleanupWorkListElement?, void> structMarshalStub;
nuint size;
if (!TryGetStructMarshalStub((IntPtr)pMT, &structMarshalStub, &size))
throw new ArgumentException(SR.Argument_MustHaveLayoutOrBeBlittable, nameof(structure));
if (structMarshalStub != null)
{
if (fDeleteOld)
{
structMarshalStub(ref structure.GetRawData(), (byte*)ptr, MarshalOperation.Cleanup, ref Unsafe.NullRef<CleanupWorkListElement?>());
}
structMarshalStub(ref structure.GetRawData(), (byte*)ptr, MarshalOperation.Marshal, ref Unsafe.NullRef<CleanupWorkListElement?>());
}
else
{
Buffer.Memmove(ref *(byte*)ptr, ref structure.GetRawData(), size);
}
}
/// <summary>
/// Helper function to copy a pointer into a preallocated structure.
/// </summary>
private static unsafe void PtrToStructureHelper(IntPtr ptr, object structure, bool allowValueClasses)
{
MethodTable* pMT = RuntimeHelpers.GetMethodTable(structure);
if (!allowValueClasses && pMT->IsValueType)
throw new ArgumentException(SR.Argument_StructMustNotBeValueClass, nameof(structure));
delegate*<ref byte, byte*, int, ref CleanupWorkListElement?, void> structMarshalStub;
nuint size;
if (!TryGetStructMarshalStub((IntPtr)pMT, &structMarshalStub, &size))
throw new ArgumentException(SR.Argument_MustHaveLayoutOrBeBlittable, nameof(structure));
if (structMarshalStub != null)
{
structMarshalStub(ref structure.GetRawData(), (byte*)ptr, MarshalOperation.Unmarshal, ref Unsafe.NullRef<CleanupWorkListElement?>());
}
else
{
Buffer.Memmove(ref structure.GetRawData(), ref *(byte*)ptr, size);
}
}
/// <summary>
/// Frees all substructures pointed to by the native memory block.
/// nameof(structuretype) is used to provide layout information.
/// </summary>
[RequiresDynamicCode("Marshalling code for the object might not be available. Use the DestroyStructure<T> overload instead.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public static unsafe void DestroyStructure(IntPtr ptr, Type structuretype)
{
ArgumentNullException.ThrowIfNull(ptr);
ArgumentNullException.ThrowIfNull(structuretype);
if (structuretype is not RuntimeType rt)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(structuretype));
if (rt.IsGenericType)
throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(structuretype));
delegate*<ref byte, byte*, int, ref CleanupWorkListElement?, void> structMarshalStub;
nuint size;
if (!TryGetStructMarshalStub(rt.GetUnderlyingNativeHandle(), &structMarshalStub, &size))
throw new ArgumentException(SR.Argument_MustHaveLayoutOrBeBlittable, nameof(structuretype));
GC.KeepAlive(rt);
if (structMarshalStub != null)
{
structMarshalStub(ref Unsafe.NullRef<byte>(), (byte*)ptr, MarshalOperation.Cleanup, ref Unsafe.NullRef<CleanupWorkListElement?>());
}
}
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_TryGetStructMarshalStub")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static unsafe partial bool TryGetStructMarshalStub(IntPtr th, delegate*<ref byte, byte*, int, ref CleanupWorkListElement?, void>* structMarshalStub, nuint* size);
// Note: Callers are required to keep obj alive
internal static unsafe bool IsPinnable(object? obj)
=> (obj == null) || !RuntimeHelpers.GetMethodTable(obj)->ContainsGCPointers;
#if TARGET_WINDOWS
internal static bool IsBuiltInComSupported { get; } = IsBuiltInComSupportedInternal();
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_IsBuiltInComSupported")]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool IsBuiltInComSupportedInternal();
/// <summary>
/// Returns the HInstance for this module. Returns -1 if the module doesn't have
/// an HInstance. In Memory (Dynamic) Modules won't have an HInstance.
/// </summary>
[RequiresAssemblyFiles("Windows only assigns HINSTANCE to assemblies loaded from disk. " +
"This API will return -1 for modules without a file on disk.")]
public static IntPtr GetHINSTANCE(Module m)
{
ArgumentNullException.ThrowIfNull(m);
if (m is RuntimeModule rtModule)
{
return GetHINSTANCE(new QCallModule(ref rtModule));
}
return (IntPtr)(-1);
}
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_GetHINSTANCE")]
private static partial IntPtr GetHINSTANCE(QCallModule m);
#endif // TARGET_WINDOWS
internal static Exception GetExceptionForHRInternal(int errorCode, IntPtr errorInfo)
{
Exception? exception = null;
GetExceptionForHRInternal(errorCode, errorInfo, ObjectHandleOnStack.Create(ref exception));
return exception!;
}
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_GetExceptionForHR")]
private static partial void GetExceptionForHRInternal(int errorCode, IntPtr errorInfo, ObjectHandleOnStack exception);
#if FEATURE_COMINTEROP
/// <summary>
/// Converts the CLR exception to an HRESULT. This function also sets
/// up an IErrorInfo for the exception.
/// </summary>
public static int GetHRForException(Exception? e)
=> GetHRForException(ObjectHandleOnStack.Create(ref e));
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_GetHRForException")]
private static partial int GetHRForException(ObjectHandleOnStack exception);
/// <summary>
/// Given a managed object that wraps an ITypeInfo, return its name.
/// </summary>
[SupportedOSPlatform("windows")]
public static string GetTypeInfoName(ITypeInfo typeInfo)
{
ArgumentNullException.ThrowIfNull(typeInfo);
typeInfo.GetDocumentation(-1, out string strTypeLibName, out _, out _, out _);
return strTypeLibName;
}
#pragma warning disable IDE0060
// This method is identical to Type.GetTypeFromCLSID. Since it's interop specific, we expose it
// on Marshal for more consistent API surface.
internal static Type? GetTypeFromCLSID(Guid clsid, string? server, bool throwOnError)
{
if (!IsBuiltInComSupported)
{
throw new NotSupportedException(SR.NotSupported_COM);
}
// Note: "throwOnError" is a vacuous parameter. Any errors due to the CLSID not being registered or the server not being found will happen
// on the Activator.CreateInstance() call. GetTypeFromCLSID() merely wraps the data in a Type object without any validation.
Type? type = null;
GetTypeFromCLSID(clsid, server, ObjectHandleOnStack.Create(ref type));
return type;
}
#pragma warning restore IDE0060
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_GetTypeFromCLSID", StringMarshalling = StringMarshalling.Utf16)]
private static partial void GetTypeFromCLSID(in Guid clsid, string? server, ObjectHandleOnStack retType);
/// <summary>
/// Return the IUnknown* for an Object if the current context is the one
/// where the RCW was first seen. Will return null otherwise.
/// </summary>
[SupportedOSPlatform("windows")]
public static IntPtr /* IUnknown* */ GetIUnknownForObject(object o)
{
ArgumentNullException.ThrowIfNull(o);
return GetIUnknownForObject(ObjectHandleOnStack.Create(ref o));
}
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_GetIUnknownForObject")]
private static partial IntPtr /* IUnknown* */ GetIUnknownForObject(ObjectHandleOnStack o);
/// <summary>
/// Return the IDispatch* for an Object.
/// </summary>
[SupportedOSPlatform("windows")]
public static IntPtr /* IDispatch */ GetIDispatchForObject(object o)
{
ArgumentNullException.ThrowIfNull(o);
return GetIDispatchForObject(ObjectHandleOnStack.Create(ref o));
}
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_GetIDispatchForObject")]
private static partial IntPtr /* IDispatch* */ GetIDispatchForObject(ObjectHandleOnStack o);
/// <summary>
/// Return the IUnknown* representing the interface for the Object.
/// Object o should support Type T
/// </summary>
[SupportedOSPlatform("windows")]
[EditorBrowsable(EditorBrowsableState.Never)]
public static IntPtr /* IUnknown* */ GetComInterfaceForObject(object o, Type T)
=> GetComInterfaceForObject(o, T, CustomQueryInterfaceMode.Allow);
[SupportedOSPlatform("windows")]
public static IntPtr GetComInterfaceForObject<T, TInterface>([DisallowNull] T o)
=> GetComInterfaceForObject(o!, typeof(TInterface), CustomQueryInterfaceMode.Allow);
/// <summary>
/// Return the IUnknown* representing the interface for the Object.
/// Object o should support Type T, it refer the value of mode to
/// invoke customized QueryInterface or not.
/// </summary>
[SupportedOSPlatform("windows")]
[EditorBrowsable(EditorBrowsableState.Never)]
public static IntPtr /* IUnknown* */ GetComInterfaceForObject(object o, Type T, CustomQueryInterfaceMode mode)
{
ArgumentNullException.ThrowIfNull(o);
ArgumentNullException.ThrowIfNull(T);
if (T is not RuntimeType rt)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(T));
return GetComInterfaceForObject(ObjectHandleOnStack.Create(ref o), new QCallTypeHandle(ref rt), fEnableCustomizedQueryInterface: mode == CustomQueryInterfaceMode.Allow);
}
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_GetComInterfaceForObject")]
private static partial IntPtr /* IUnknown* */ GetComInterfaceForObject(ObjectHandleOnStack o, QCallTypeHandle t, [MarshalAs(UnmanagedType.Bool)] bool fEnableCustomizedQueryInterface);
/// <summary>
/// Return the managed object representing the IUnknown*
/// </summary>
[SupportedOSPlatform("windows")]
public static object GetObjectForIUnknown(IntPtr /* IUnknown* */ pUnk)
{
ArgumentNullException.ThrowIfNull(pUnk);
object? retObject = null;
GetObjectForIUnknown(pUnk, ObjectHandleOnStack.Create(ref retObject));
return retObject!;
}
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_GetObjectForIUnknown")]
private static partial void GetObjectForIUnknown(IntPtr /* IUnknown* */ pUnk, ObjectHandleOnStack retObject);
[SupportedOSPlatform("windows")]
public static object GetUniqueObjectForIUnknown(IntPtr unknown)
{
ArgumentNullException.ThrowIfNull(unknown);
object? retObject = null;
GetUniqueObjectForIUnknown(unknown, ObjectHandleOnStack.Create(ref retObject));
return retObject!;
}
/// <summary>
/// Return a unique Object given an IUnknown. This ensures that you receive a fresh
/// object (we will not look in the cache to match up this IUnknown to an already
/// existing object). This is useful in cases where you want to be able to call
/// ReleaseComObject on a RCW and not worry about other active uses ofsaid RCW.
/// </summary>
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_GetUniqueObjectForIUnknown")]
private static partial void GetUniqueObjectForIUnknown(IntPtr unknown, ObjectHandleOnStack retObject);
/// <summary>
/// Return an Object for IUnknown, using the Type T.
/// Type T should be either a COM imported Type or a sub-type of COM imported Type
/// </summary>
[SupportedOSPlatform("windows")]
public static object GetTypedObjectForIUnknown(IntPtr /* IUnknown* */ pUnk, Type t)
{
ArgumentNullException.ThrowIfNull(pUnk);
ArgumentNullException.ThrowIfNull(t);
if (t is not RuntimeType rt)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(t));
object? retObject = null;
GetTypedObjectForIUnknown(pUnk, new QCallTypeHandle(ref rt), ObjectHandleOnStack.Create(ref retObject));
return retObject!;
}
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_GetTypedObjectForIUnknown")]
private static partial void GetTypedObjectForIUnknown(IntPtr /* IUnknown* */ pUnk, QCallTypeHandle t, ObjectHandleOnStack retObject);
[SupportedOSPlatform("windows")]
[EditorBrowsable(EditorBrowsableState.Never)]
public static IntPtr CreateAggregatedObject(IntPtr pOuter, object o)
{
if (!IsBuiltInComSupported)
{
throw new NotSupportedException(SR.NotSupported_COM);
}
ArgumentNullException.ThrowIfNull(pOuter);
ArgumentNullException.ThrowIfNull(o);
return CreateAggregatedObject(pOuter, ObjectHandleOnStack.Create(ref o));
}
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_CreateAggregatedObject")]
private static partial IntPtr CreateAggregatedObject(IntPtr pOuter, ObjectHandleOnStack o);
[SupportedOSPlatform("windows")]
public static IntPtr CreateAggregatedObject<T>(IntPtr pOuter, T o) where T : notnull
{
if (!IsBuiltInComSupported)
{
throw new NotSupportedException(SR.NotSupported_COM);
}
return CreateAggregatedObject(pOuter, (object)o);
}
public static void CleanupUnusedObjectsInCurrentContext()
=> InternalCleanupUnusedObjectsInCurrentContext();
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_CleanupUnusedObjectsInCurrentContext")]
private static partial void InternalCleanupUnusedObjectsInCurrentContext();
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern bool AreComObjectsAvailableForCleanup();
/// <summary>
/// Checks if the object is classic COM component.
/// </summary>
public static bool IsComObject(object o)
{
ArgumentNullException.ThrowIfNull(o);
return o is __ComObject;
}
/// <summary>
/// Release the COM component and if the reference hits 0 zombie this object.
/// Further usage of this Object might throw an exception
/// </summary>
[SupportedOSPlatform("windows")]
public static int ReleaseComObject(object o)
{
if (!IsBuiltInComSupported)
{
throw new NotSupportedException(SR.NotSupported_COM);
}
if (o is null)
{
// Match .NET Framework behaviour.
throw new NullReferenceException();
}
if (!(o is __ComObject co))
{
throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o));
}
return ReleaseComObject(ObjectHandleOnStack.Create(ref co));
}
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_ReleaseComObject")]
private static partial int ReleaseComObject(ObjectHandleOnStack o);
/// <summary>
/// Release the COM component and zombie this object.
/// Further usage of this Object might throw an exception
/// </summary>
[SupportedOSPlatform("windows")]
public static int FinalReleaseComObject(object o)
{
if (!IsBuiltInComSupported)
{
throw new NotSupportedException(SR.NotSupported_COM);
}
ArgumentNullException.ThrowIfNull(o);
if (!(o is __ComObject co))
{
throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o));
}
FinalReleaseComObject(ObjectHandleOnStack.Create(ref co));
return 0;
}
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_FinalReleaseComObject")]
private static partial void FinalReleaseComObject(ObjectHandleOnStack o);
[SupportedOSPlatform("windows")]
public static object? GetComObjectData(object obj, object key)
{
if (!IsBuiltInComSupported)
{
throw new NotSupportedException(SR.NotSupported_COM);
}
ArgumentNullException.ThrowIfNull(obj);
ArgumentNullException.ThrowIfNull(key);
if (!(obj is __ComObject co))
{
throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(obj));
}
// Retrieve the data from the __ComObject.
return co.GetData(key);
}
/// <summary>
/// Sets data on the COM object. The data can only be set once for a given key
/// and cannot be removed. This function returns true if the data has been added,
/// false if the data could not be added because there already was data for the
/// specified key.
/// </summary>
[SupportedOSPlatform("windows")]
public static bool SetComObjectData(object obj, object key, object? data)
{
if (!IsBuiltInComSupported)
{
throw new NotSupportedException(SR.NotSupported_COM);
}
ArgumentNullException.ThrowIfNull(obj);
ArgumentNullException.ThrowIfNull(key);
if (!(obj is __ComObject co))
{
throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(obj));
}
// Retrieve the data from the __ComObject.
return co.SetData(key, data);
}
/// <summary>
/// This method takes the given COM object and wraps it in an object
/// of the specified type. The type must be derived from __ComObject.
/// </summary>
[SupportedOSPlatform("windows")]
[EditorBrowsable(EditorBrowsableState.Never)]
[return: NotNullIfNotNull(nameof(o))]
public static object? CreateWrapperOfType(object? o, Type t)
{
if (!IsBuiltInComSupported)
{
throw new NotSupportedException(SR.NotSupported_COM);
}
ArgumentNullException.ThrowIfNull(t);
if (!t.IsCOMObject)
{
throw new ArgumentException(SR.Argument_TypeNotComObject, nameof(t));
}
if (t.IsGenericType)
{
throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t));
}
if (o is null)
{
return null;
}
if (!o.GetType().IsCOMObject)
{
throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o));
}
// Check to see if we have nothing to do.
if (o.GetType() == t)
{
return o;
}
// Check to see if we already have a cached wrapper for this type.
object? Wrapper = GetComObjectData(o, t);
if (Wrapper is null)
{
// Create the wrapper for the specified type.
Wrapper = InternalCreateWrapperOfType(o, t);
// Attempt to cache the wrapper on the object.
if (!SetComObjectData(o, t, Wrapper))
{
// Another thread already cached the wrapper so use that one instead.
Wrapper = GetComObjectData(o, t)!;
}
}
return Wrapper;
}
[SupportedOSPlatform("windows")]
public static TWrapper CreateWrapperOfType<T, TWrapper>(T? o)
{
if (!IsBuiltInComSupported)
{
throw new NotSupportedException(SR.NotSupported_COM);
}
return (TWrapper)CreateWrapperOfType(o, typeof(TWrapper))!;
}
private static object InternalCreateWrapperOfType(object o, Type t)
{
if (t is not RuntimeType rt)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(t));
object? retObject = null;
InternalCreateWrapperOfType(ObjectHandleOnStack.Create(ref o), new QCallTypeHandle(ref rt), ObjectHandleOnStack.Create(ref retObject));
return retObject!;
}
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_InternalCreateWrapperOfType")]
private static partial void InternalCreateWrapperOfType(ObjectHandleOnStack o, QCallTypeHandle rt, ObjectHandleOnStack retObject);
/// <summary>
/// check if the type is visible from COM.
/// </summary>
public static bool IsTypeVisibleFromCom(Type t)
{
ArgumentNullException.ThrowIfNull(t);
if (t is not RuntimeType rt)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(t));
return IsTypeVisibleFromCom(new QCallTypeHandle(ref rt));
}
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_IsTypeVisibleFromCom")]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool IsTypeVisibleFromCom(QCallTypeHandle rt);
[SupportedOSPlatform("windows")]
[EditorBrowsable(EditorBrowsableState.Never)]
public static void GetNativeVariantForObject(object? obj, /* VARIANT * */ IntPtr pDstNativeVariant)
{
if (!IsBuiltInComSupported)
{
throw new NotSupportedException(SR.NotSupported_COM);
}
ArgumentNullException.ThrowIfNull(pDstNativeVariant);
GetNativeVariantForObject(ObjectHandleOnStack.Create(ref obj), pDstNativeVariant);
}
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_GetNativeVariantForObject")]
private static partial void GetNativeVariantForObject(ObjectHandleOnStack obj, /* VARIANT * */ IntPtr pDstNativeVariant);
[SupportedOSPlatform("windows")]
[EditorBrowsable(EditorBrowsableState.Never)]
public static void GetNativeVariantForObject<T>(T? obj, IntPtr pDstNativeVariant)
{
if (!IsBuiltInComSupported)
{
throw new NotSupportedException(SR.NotSupported_COM);
}
GetNativeVariantForObject((object?)obj, pDstNativeVariant);
}
[SupportedOSPlatform("windows")]
[EditorBrowsable(EditorBrowsableState.Never)]
public static object? GetObjectForNativeVariant(/* VARIANT * */ IntPtr pSrcNativeVariant)
{
if (!IsBuiltInComSupported)
{
throw new NotSupportedException(SR.NotSupported_COM);
}
ArgumentNullException.ThrowIfNull(pSrcNativeVariant);
object? retObject = null;
GetObjectForNativeVariant(pSrcNativeVariant, ObjectHandleOnStack.Create(ref retObject));
return retObject;
}
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_GetObjectForNativeVariant")]
private static partial void GetObjectForNativeVariant(/* VARIANT * */ IntPtr pSrcNativeVariant, ObjectHandleOnStack retObject);
[SupportedOSPlatform("windows")]
[EditorBrowsable(EditorBrowsableState.Never)]
public static T? GetObjectForNativeVariant<T>(IntPtr pSrcNativeVariant)
{
if (!IsBuiltInComSupported)
{
throw new NotSupportedException(SR.NotSupported_COM);
}
return (T?)GetObjectForNativeVariant(pSrcNativeVariant);
}
[SupportedOSPlatform("windows")]
[EditorBrowsable(EditorBrowsableState.Never)]
public static object?[] GetObjectsForNativeVariants(/* VARIANT * */ IntPtr aSrcNativeVariant, int cVars)
{
if (!IsBuiltInComSupported)
{
throw new NotSupportedException(SR.NotSupported_COM);
}
ArgumentNullException.ThrowIfNull(aSrcNativeVariant);
ArgumentOutOfRangeException.ThrowIfNegative(cVars);
object?[]? retArray = null;
GetObjectsForNativeVariants(aSrcNativeVariant, cVars, ObjectHandleOnStack.Create(ref retArray));
return retArray!;
}
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_GetObjectsForNativeVariants")]
private static partial void GetObjectsForNativeVariants(/* VARIANT * */ IntPtr aSrcNativeVariant, int cVars, ObjectHandleOnStack retArray);
[SupportedOSPlatform("windows")]
[EditorBrowsable(EditorBrowsableState.Never)]
public static T[] GetObjectsForNativeVariants<T>(IntPtr aSrcNativeVariant, int cVars)
{
if (!IsBuiltInComSupported)
{
throw new NotSupportedException(SR.NotSupported_COM);
}
object?[] objects = GetObjectsForNativeVariants(aSrcNativeVariant, cVars);
T[] result = new T[objects.Length];
Array.Copy(objects, result, objects.Length);
return result;
}
/// <summary>
/// <para>Returns the first valid COM slot that GetMethodInfoForSlot will work on
/// This will be 3 for IUnknown based interfaces and 7 for IDispatch based interfaces. </para>
/// </summary>
[SupportedOSPlatform("windows")]
public static int GetStartComSlot(Type t)
{
ArgumentNullException.ThrowIfNull(t);
if (t is not RuntimeType rt)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(t));
return GetStartComSlot(new QCallTypeHandle(ref rt));
}
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_GetStartComSlot")]
private static partial int GetStartComSlot(QCallTypeHandle rt);
/// <summary>
/// <para>Returns the last valid COM slot that GetMethodInfoForSlot will work on. </para>
/// </summary>
[SupportedOSPlatform("windows")]
public static int GetEndComSlot(Type t)
{
ArgumentNullException.ThrowIfNull(t);
if (t is not RuntimeType rt)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(t));
return GetEndComSlot(new QCallTypeHandle(ref rt));
}
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_GetEndComSlot")]
private static partial int GetEndComSlot(QCallTypeHandle rt);
[RequiresUnreferencedCode("Built-in COM support is not trim compatible", Url = "https://aka.ms/dotnet-illink/com")]
[SupportedOSPlatform("windows")]
public static object BindToMoniker(string monikerName)
{
if (!IsBuiltInComSupported)
{
throw new NotSupportedException(SR.NotSupported_COM);
}
ThrowExceptionForHR(CreateBindCtx(0, out IntPtr bindctx));
try
{
ThrowExceptionForHR(MkParseDisplayName(bindctx, monikerName, out _, out IntPtr pmoniker));
try
{
ThrowExceptionForHR(BindMoniker(pmoniker, 0, ref IID_IUnknown, out IntPtr ptr));
try
{
return GetObjectForIUnknown(ptr);
}
finally
{
Release(ptr);
}
}
finally
{
Release(pmoniker);
}
}
finally
{
Release(bindctx);
}
}
[LibraryImport(Interop.Libraries.Ole32)]
private static partial int CreateBindCtx(uint reserved, out IntPtr ppbc);
[LibraryImport(Interop.Libraries.Ole32)]
private static partial int MkParseDisplayName(IntPtr pbc, [MarshalAs(UnmanagedType.LPWStr)] string szUserName, out uint pchEaten, out IntPtr ppmk);
[LibraryImport(Interop.Libraries.Ole32)]
private static partial int BindMoniker(IntPtr pmk, uint grfOpt, ref Guid iidResult, out IntPtr ppvResult);
[SupportedOSPlatform("windows")]
public static void ChangeWrapperHandleStrength(object otp, bool fIsWeak)
{
ArgumentNullException.ThrowIfNull(otp);
ChangeWrapperHandleStrength(ObjectHandleOnStack.Create(ref otp), fIsWeak);
}
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_ChangeWrapperHandleStrength")]
private static partial void ChangeWrapperHandleStrength(ObjectHandleOnStack otp, [MarshalAs(UnmanagedType.Bool)] bool fIsWeak);
#endif // FEATURE_COMINTEROP
internal static Delegate GetDelegateForFunctionPointerInternal(IntPtr ptr, RuntimeType t)
{
Delegate? retDelegate = null;
GetDelegateForFunctionPointerInternal(ptr, new QCallTypeHandle(ref t), ObjectHandleOnStack.Create(ref retDelegate));
return retDelegate!;
}
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_GetDelegateForFunctionPointerInternal")]
private static partial void GetDelegateForFunctionPointerInternal(IntPtr ptr, QCallTypeHandle t, ObjectHandleOnStack retDelegate);
internal static IntPtr GetFunctionPointerForDelegateInternal(Delegate d)
{
return GetFunctionPointerForDelegateInternal(ObjectHandleOnStack.Create(ref d));
}
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_GetFunctionPointerForDelegateInternal")]
private static partial IntPtr GetFunctionPointerForDelegateInternal(ObjectHandleOnStack d);
#if DEBUG // Used for testing in Checked or Debug
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_GetIsInCooperativeGCModeFunctionPointer")]
internal static unsafe partial delegate* unmanaged<int> GetIsInCooperativeGCModeFunctionPointer();
#endif
}
}