Welcome to mirror list, hosted at ThFree Co, Russian Federation.

McgMarshal.cs « Shared « src « System.Private.Interop « src - github.com/mono/corert.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 40ddc4f9de10eb733c6b5e5964339d29f5af5387 (plain)
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
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ----------------------------------------------------------------------------------
// Interop library code
//
// Marshalling helpers used by MCG generated stub
// McgMarshal covers full marshalling surface area and is entrypoint for all marshalling support.
// In long term:
//  1. MCG generated code should  call McgMarshal to do marshalling
//  2. Public Marhshal API should call McgMarshal to do marshalling

// NOTE:
//   These source code are being published to InternalAPIs and consumed by RH builds
//   Use PublishInteropAPI.bat to keep the InternalAPI copies in sync
// ----------------------------------------------------------------------------------

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.InteropServices;
using System.Threading;
using System.Text;
using System.Runtime;
using System.Runtime.CompilerServices;
using Internal.NativeFormat;

#if !CORECLR
using Internal.Runtime.Augments;
#endif

#if RHTESTCL
using OutputClass = System.Console;
#else
using OutputClass = System.Diagnostics.Debug;
#endif

namespace System.Runtime.InteropServices
{
    /// <summary>
    /// Expose functionality from System.Private.CoreLib and forwards calls to InteropExtensions in System.Private.CoreLib
    /// </summary>
    [CLSCompliant(false)]
    public static partial class McgMarshal
    {
        public static void SaveLastWin32Error()
        {
            PInvokeMarshal.SaveLastWin32Error();
        }

        public static void ClearLastWin32Error()
        {
            PInvokeMarshal.ClearLastWin32Error();
        }

        public static bool GuidEquals(ref Guid left, ref Guid right)
        {
            return InteropExtensions.GuidEquals(ref left, ref right);
        }

        public static bool ComparerEquals<T>(T left, T right)
        {
            return InteropExtensions.ComparerEquals<T>(left, right);
        }

        public static T CreateClass<T>() where T : class
        {
            return InteropExtensions.UncheckedCast<T>(InteropExtensions.RuntimeNewObject(typeof(T).TypeHandle));
        }

        public static bool IsEnum(object obj)
        {
#if RHTESTCL
            return false;
#else
            return InteropExtensions.IsEnum(obj.GetTypeHandle());
#endif
        }

        /// <summary>
        /// Return true if the type is __COM or derived from __COM. False otherwise
        /// </summary>
        public static bool IsComObject(Type type)
        {
#if RHTESTCL
            return false;
#else
            return type == typeof(__ComObject) || type.GetTypeInfo().IsSubclassOf(typeof(__ComObject));
#endif
        }

        /// <summary>
        /// Return true if the object is a RCW. False otherwise
        /// </summary>
        internal static bool IsComObject(object obj)
        {
            return (obj is __ComObject);
        }

        public static T FastCast<T>(object value) where T : class
        {
            // We have an assert here, to verify that a "real" cast would have succeeded.
            // However, casting on weakly-typed RCWs modifies their state, by doing a QI and caching
            // the result.  This often makes things work which otherwise wouldn't work (especially variance).
            Debug.Assert(value == null || value is T);
            return InteropExtensions.UncheckedCast<T>(value);
        }

        /// <summary>
        /// Converts a managed DateTime to native OLE datetime
        /// Used by MCG marshalling code
        /// </summary>
        public static double ToNativeOleDate(DateTime dateTime)
        {
            return InteropExtensions.ToNativeOleDate(dateTime);
        }

        /// <summary>
        /// Converts native OLE datetime to managed DateTime
        /// Used by MCG marshalling code
        /// </summary>
        public static DateTime FromNativeOleDate(double nativeOleDate)
        {
            return InteropExtensions.FromNativeOleDate(nativeOleDate);
        }

        /// <summary>
        /// Used in Marshalling code
        /// Call safeHandle.InitializeHandle to set the internal _handle field
        /// </summary>
        public static void InitializeHandle(SafeHandle safeHandle, IntPtr win32Handle)
        {
            InteropExtensions.InitializeHandle(safeHandle, win32Handle);
        }

        /// <summary>
        /// Check if obj's type is the same as represented by normalized handle
        /// </summary>
        [MethodImpl(MethodImplOptions.NoInlining)]
        public static bool IsOfType(object obj, RuntimeTypeHandle handle)
        {
            return obj.IsOfType(handle);
        }

#if ENABLE_MIN_WINRT
        public static unsafe void SetExceptionErrorCode(Exception exception, int errorCode)	
        {
            InteropExtensions.SetExceptionErrorCode(exception, errorCode);
        }

        /// <summary>
        /// Used in Marshalling code
        /// Gets the handle of the CriticalHandle
        /// </summary>
        public static IntPtr GetHandle(CriticalHandle criticalHandle)
        {
            return InteropExtensions.GetCriticalHandle(criticalHandle);
        }

        /// <summary>
        /// Used in Marshalling code
        /// Sets the handle of the CriticalHandle
        /// </summary>
        public static void SetHandle(CriticalHandle criticalHandle, IntPtr handle)
        {
            InteropExtensions.SetCriticalHandle(criticalHandle, handle);
        }
#endif
    }

    /// <summary>
    /// McgMarshal helpers exposed to be used by MCG
    /// </summary>
    public static partial class McgMarshal
    {
        #region Type marshalling

        public static Type TypeNameToType(HSTRING nativeTypeName, int nativeTypeKind)
        {
#if ENABLE_WINRT
            return McgTypeHelpers.TypeNameToType(nativeTypeName, nativeTypeKind);
#else
            throw new NotSupportedException("TypeNameToType");
#endif
        }

        internal static Type TypeNameToType(string nativeTypeName, int nativeTypeKind)
        {
#if ENABLE_WINRT
            return McgTypeHelpers.TypeNameToType(nativeTypeName, nativeTypeKind, checkTypeKind: false);
#else
            throw new NotSupportedException("TypeNameToType");
#endif
        }

        public static unsafe void TypeToTypeName(
            Type type,
            out HSTRING nativeTypeName,
            out int nativeTypeKind)
        {
#if ENABLE_WINRT
            McgTypeHelpers.TypeToTypeName(type, out nativeTypeName, out nativeTypeKind);
#else
            throw new NotSupportedException("TypeToTypeName");
#endif
        }

        /// <summary>
        /// Fetch type name
        /// </summary>
        /// <param name="typeHandle">type</param>
        /// <returns>type name</returns>
        internal static string TypeToTypeName(RuntimeTypeHandle typeHandle, out int nativeTypeKind)
        {
#if ENABLE_WINRT
            TypeKind typekind;
            string typeName;
            McgTypeHelpers.TypeToTypeName(typeHandle, out typeName, out typekind);
            nativeTypeKind = (int)typekind;
            return typeName;
#else
           throw new NotSupportedException("TypeToTypeName");
#endif
        }

        #endregion

        #region String marshalling

        [CLSCompliant(false)]
        public static unsafe void StringBuilderToUnicodeString(System.Text.StringBuilder stringBuilder, ushort* destination)
        {
            PInvokeMarshal.StringBuilderToUnicodeString(stringBuilder, destination);
        }

        [CLSCompliant(false)]
        public static unsafe void UnicodeStringToStringBuilder(ushort* newBuffer, System.Text.StringBuilder stringBuilder)
        {
            PInvokeMarshal.UnicodeStringToStringBuilder(newBuffer, stringBuilder);
        }

#if !RHTESTCL

        [CLSCompliant(false)]
        public static unsafe void StringBuilderToAnsiString(System.Text.StringBuilder stringBuilder, byte* pNative,
            bool bestFit, bool throwOnUnmappableChar)
        {
            PInvokeMarshal.StringBuilderToAnsiString(stringBuilder, pNative, bestFit, throwOnUnmappableChar);
        }

        [CLSCompliant(false)]
        public static unsafe void AnsiStringToStringBuilder(byte* newBuffer, System.Text.StringBuilder stringBuilder)
        {
            PInvokeMarshal.AnsiStringToStringBuilder(newBuffer, stringBuilder);
        }

        /// <summary>
        /// Convert ANSI string to unicode string, with option to free native memory. Calls generated by MCG
        /// </summary>
        /// <remarks>Input assumed to be zero terminated. Generates String.Empty for zero length string.
        /// This version is more efficient than ConvertToUnicode in src\Interop\System\Runtime\InteropServices\Marshal.cs in that it can skip calling
        /// MultiByteToWideChar for ASCII string, and it does not need another char[] buffer</remarks>
        [CLSCompliant(false)]
        public static unsafe string AnsiStringToString(byte* pchBuffer)
        {
            return PInvokeMarshal.AnsiStringToString(pchBuffer);
        }

        /// <summary>
        /// Convert UNICODE string to ANSI string.
        /// </summary>
        /// <remarks>This version is more efficient than StringToHGlobalAnsi in Interop\System\Runtime\InteropServices\Marshal.cs in that
        /// it could allocate single byte per character, instead of SystemMaxDBCSCharSize per char, and it can skip calling WideCharToMultiByte for ASCII string</remarks>
        [CLSCompliant(false)]
        public static unsafe byte* StringToAnsiString(string str, bool bestFit, bool throwOnUnmappableChar)
        {
            return PInvokeMarshal.StringToAnsiString(str, bestFit, throwOnUnmappableChar);
        }

        /// <summary>
        /// Convert UNICODE wide char array to ANSI ByVal byte array.
        /// </summary>
        /// <remarks>
        /// * This version works with array instead string, it means that there will be NO NULL to terminate the array.
        /// * The buffer to store the byte array must be allocated by the caller and must fit managedArray.Length.
        /// </remarks>
        /// <param name="managedArray">UNICODE wide char array</param>
        /// <param name="pNative">Allocated buffer where the ansi characters must be placed. Could NOT be null. Buffer size must fit char[].Length.</param>
        [CLSCompliant(false)]
        public static unsafe void ByValWideCharArrayToAnsiCharArray(char[] managedArray, byte* pNative, int expectedCharCount,
            bool bestFit, bool throwOnUnmappableChar)
        {
            PInvokeMarshal.ByValWideCharArrayToAnsiCharArray(managedArray, pNative, expectedCharCount, bestFit, throwOnUnmappableChar);
        }

        [CLSCompliant(false)]
        public static unsafe void ByValAnsiCharArrayToWideCharArray(byte* pNative, char[] managedArray)
        {
            PInvokeMarshal.ByValAnsiCharArrayToWideCharArray(pNative, managedArray);
        }

        [CLSCompliant(false)]
        public static unsafe void WideCharArrayToAnsiCharArray(char[] managedArray, byte* pNative, bool bestFit, bool throwOnUnmappableChar)
        {
            PInvokeMarshal.WideCharArrayToAnsiCharArray(managedArray, pNative, bestFit, throwOnUnmappableChar);
        }

        /// <summary>
        /// Convert ANSI ByVal byte array to UNICODE wide char array, best fit
        /// </summary>
        /// <remarks>
        /// * This version works with array instead to string, it means that the len must be provided and there will be NO NULL to
        /// terminate the array.
        /// * The buffer to the UNICODE wide char array must be allocated by the caller.
        /// </remarks>
        /// <param name="pNative">Pointer to the ANSI byte array. Could NOT be null.</param>
        /// <param name="lenInBytes">Maximum buffer size.</param>
        /// <param name="managedArray">Wide char array that has already been allocated.</param>
        [CLSCompliant(false)]
        public static unsafe void AnsiCharArrayToWideCharArray(byte* pNative, char[] managedArray)
        {
            PInvokeMarshal.AnsiCharArrayToWideCharArray(pNative, managedArray);
        }

        /// <summary>
        /// Convert a single UNICODE wide char to a single ANSI byte.
        /// </summary>
        /// <param name="managedArray">single UNICODE wide char value</param>
        public static unsafe byte WideCharToAnsiChar(char managedValue, bool bestFit, bool throwOnUnmappableChar)
        {
            return PInvokeMarshal.WideCharToAnsiChar(managedValue, bestFit, throwOnUnmappableChar);
        }

        /// <summary>
        /// Convert a single ANSI byte value to a single UNICODE wide char value, best fit.
        /// </summary>
        /// <param name="nativeValue">Single ANSI byte value.</param>
        public static unsafe char AnsiCharToWideChar(byte nativeValue)
        {
            return PInvokeMarshal.AnsiCharToWideChar(nativeValue);
        }

        /// <summary>
        /// Convert UNICODE string to ANSI ByVal string.
        /// </summary>
        /// <remarks>This version is more efficient than StringToHGlobalAnsi in Interop\System\Runtime\InteropServices\Marshal.cs in that
        /// it could allocate single byte per character, instead of SystemMaxDBCSCharSize per char, and it can skip calling WideCharToMultiByte for ASCII string</remarks>
        /// <param name="str">Unicode string.</param>
        /// <param name="pNative"> Allocated buffer where the ansi string must be placed. Could NOT be null. Buffer size must fit str.Length.</param>
        [CLSCompliant(false)]
        public static unsafe void StringToByValAnsiString(string str, byte* pNative, int charCount, bool bestFit, bool throwOnUnmappableChar)
        {
            PInvokeMarshal.StringToByValAnsiString(str, pNative, charCount, bestFit, throwOnUnmappableChar);
        }

        /// <summary>
        /// Convert ANSI string to unicode string, with option to free native memory. Calls generated by MCG
        /// </summary>
        /// <remarks>Input assumed to be zero terminated. Generates String.Empty for zero length string.
        /// This version is more efficient than ConvertToUnicode in src\Interop\System\Runtime\InteropServices\Marshal.cs in that it can skip calling
        /// MultiByteToWideChar for ASCII string, and it does not need another char[] buffer</remarks>
        [CLSCompliant(false)]
        public static unsafe string ByValAnsiStringToString(byte* pchBuffer, int charCount)
        {
            return PInvokeMarshal.ByValAnsiStringToString(pchBuffer, charCount);
        }

        /// <summary>
        /// CoTaskMemAlloc + ZeroMemory
        /// @TODO - we can probably optimize the zero memory part later
        /// </summary>
        public unsafe static void* CoTaskMemAllocAndZeroMemory(IntPtr size)
        {
            void *ptr = (void*)PInvokeMarshal.CoTaskMemAlloc(new UIntPtr((void*)size));
            if (ptr == null)
                return ptr;

            byte *pByte = (byte*)ptr;
            long lSize = size.ToInt64();
            while (lSize > 0)
            {
                lSize--;
                (*pByte++) = 0;
            }

            return ptr;
        }

        /// <summary>
        /// Free allocated memory. The allocated memory should be allocated by CoTaskMemAlloc
        /// </summary>
        public static void SafeCoTaskMemFree(IntPtr allocatedMemory)
        {
            if (allocatedMemory != IntPtr.Zero)
                PInvokeMarshal.CoTaskMemFree(allocatedMemory);
        }

        /// <summary>
        /// Free allocated memory. The allocated memory should be allocated by CoTaskMemAlloc
        /// </summary>
        public static unsafe void SafeCoTaskMemFree(void* pv)
        {
            if (pv != null)
                PInvokeMarshal.CoTaskMemFree(new IntPtr(pv));
        }

        /// <summary>
        /// Allocate a buffer with enough size to store the unicode characters saved in source
        /// Buffer is allocated with CoTaskMemAlloc
        /// </summary>
        public unsafe static void *AllocUnicodeBuffer(string source)
        {
            if (source == null)
                return null;

            int byteLen = checked((source.Length + 1) * 2);

            char* pBuf = (char*)PInvokeMarshal.CoTaskMemAlloc(new UIntPtr((uint)byteLen));
            if (pBuf == null)
                throw new System.OutOfMemoryException();

            return pBuf;
        }

        /// <summary>
        /// Copy unicode characters in source into dest, and terminating with null
        /// </summary>
        public unsafe static void CopyUnicodeString(string source, void* _dest)
        {
            if (source == null)
                return;

            char* dest = (char *)_dest;
            fixed (char* pSource = source)
            {
                int len = source.Length;
                char* src = pSource;

                // Copy characters one by one, including the null terminator
                for (int i = 0; i <= len; ++i)
                {
                    *(dest++) = *(src++);
                }
            }
        }

        /// <summary>
        /// Convert String to BSTR 
        /// </summary>
        public unsafe static ushort* ConvertStringToBSTR(
                ushort* ptrToFirstCharInBSTR,
                string strManaged)
        {
            if (strManaged == null)
                return null;

            if (ptrToFirstCharInBSTR == null)
            {
                // If caller don't provided buffer, allocate the buffer and create string using SysAllocStringLen
                fixed (char* ch = strManaged)
                {
                    return (ushort*) ExternalInterop.SysAllocStringLen(ch, (uint)strManaged.Length);
                }
            }
            else 
            {
                // If caller provided a buffer, construct the BSTR manually. 

                // set length
                *((int*)ptrToFirstCharInBSTR - 1) = checked(strManaged.Length * 2);

                // copy characters from the managed string
                fixed (char* ch = strManaged)
                {
                    InteropExtensions.Memcpy(
                        (System.IntPtr)ptrToFirstCharInBSTR,
                        (System.IntPtr)ch,
                        (strManaged.Length + 1) * 2);
                }

                return ptrToFirstCharInBSTR;
            }
        }

        /// <summary>
        /// Convert BSTR to String 
        /// </summary>
        public unsafe static string ConvertBSTRToString(ushort* bstr)
        {
            if (bstr == null)
                return null;
            return new string((char*)bstr, 0, (int)ExternalInterop.SysStringLen(bstr));
        }

        /// <summary>
        /// Free Allocated BSTR
        /// </summary>
        public static unsafe void SysFreeString(void* pBSTR)
        {
            SysFreeString(new IntPtr(pBSTR));
        }

        /// <summary>
        /// Free Allocated BSTR
        /// </summary>
        public unsafe static void SysFreeString(IntPtr pBSTR)
        {
            ExternalInterop.SysFreeString(pBSTR);
        } 
#endif

#if ENABLE_MIN_WINRT
       
        [MethodImplAttribute(MethodImplOptions.NoInlining)]
        public static unsafe HSTRING StringToHString(string sourceString)
        {
            if (sourceString == null)
                throw new ArgumentNullException(nameof(sourceString), SR.Null_HString);

            return StringToHStringInternal(sourceString);
        }

        [MethodImplAttribute(MethodImplOptions.NoInlining)]
        public static unsafe HSTRING StringToHStringForField(string sourceString)
        {
#if !RHTESTCL
            if (sourceString == null)
                throw new MarshalDirectiveException(SR.BadMarshalField_Null_HString);
#endif
            return StringToHStringInternal(sourceString);
        }

        private static unsafe HSTRING StringToHStringInternal(string sourceString)
        {
            HSTRING ret;
            int hr = StringToHStringNoNullCheck(sourceString, &ret);
            if (hr < 0)
                throw Marshal.GetExceptionForHR(hr);

            return ret;
        }

        [MethodImplAttribute(MethodImplOptions.NoInlining)]
        internal static unsafe int StringToHStringNoNullCheck(string sourceString, HSTRING* hstring)
        {
            fixed (char* pChars = sourceString)
            {
                int hr = ExternalInterop.WindowsCreateString(pChars, (uint)sourceString.Length, (void*)hstring);

                return hr;
            }
        }
#endif //ENABLE_MIN_WINRT

#endregion

        #region COM marshalling

        /// <summary>
        /// Explicit AddRef for RCWs
        /// You can't call IFoo.AddRef anymore as IFoo no longer derive from IUnknown
        /// You need to call McgMarshal.AddRef();
        /// </summary>
        /// <remarks>
        /// Used by prefast MCG plugin (mcgimportpft) only
        /// </remarks>
        [CLSCompliant(false)]
        public static int AddRef(__ComObject obj)
        {
            return obj.AddRef();
        }

        /// <summary>
        /// Explicit Release for RCWs
        /// You can't call IFoo.Release anymore as IFoo no longer derive from IUnknown
        /// You need to call McgMarshal.Release();
        /// </summary>
        /// <remarks>
        /// Used by prefast MCG plugin (mcgimportpft) only
        /// </remarks>
        [CLSCompliant(false)]
        public static int Release(__ComObject obj)
        {
            return obj.Release();
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        public static unsafe int ComAddRef(IntPtr pComItf)
        {
            return CalliIntrinsics.StdCall__AddRef(((__com_IUnknown*)(void*)pComItf)->pVtable->
                pfnAddRef, pComItf);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static unsafe int ComRelease_StdCall(IntPtr pComItf)
        {
            return CalliIntrinsics.StdCall__Release(((__com_IUnknown*)(void*)pComItf)->pVtable->
                pfnRelease, pComItf);
        }

        /// <summary>
        /// Inline version of ComRelease
        /// </summary>
        [MethodImpl(MethodImplOptions.NoInlining)] //reduces MCG-generated code size
        public static unsafe int ComRelease(IntPtr pComItf)
        {
            IntPtr pRelease = ((__com_IUnknown*)(void*)pComItf)->pVtable->pfnRelease;

            // Check if the COM object is implemented by PN Interop code, for which we can call directly
            if (pRelease == AddrOfIntrinsics.AddrOf<AddrOfRelease>(__vtable_IUnknown.Release))
            {
                return __interface_ccw.DirectRelease(pComItf);
            }

            // Normal slow path, do not inline
            return ComRelease_StdCall(pComItf);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        public static unsafe int ComSafeRelease(IntPtr pComItf)
        {
            if (pComItf != default(IntPtr))
            {
                return ComRelease(pComItf);
            }

            return 0;
        }

        public static int FinalReleaseComObject(object o)
        {
            if (o == null)
                throw new ArgumentNullException(nameof(o));

            __ComObject co = null;

            // Make sure the obj is an __ComObject.
            try
            {
                co = (__ComObject)o;
            }
            catch (InvalidCastException)
            {
                throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o));
            }
            co.FinalReleaseSelf();
            return 0;
        }


        /// <summary>
        /// Returns the cached WinRT factory RCW under the current context
        /// </summary>
        [CLSCompliant(false)]
        public static unsafe __ComObject GetActivationFactory(string className, RuntimeTypeHandle factoryIntf)
        {
#if ENABLE_MIN_WINRT
            return FactoryCache.Get().GetActivationFactory(className, factoryIntf);
#else
            throw new PlatformNotSupportedException("GetActivationFactory");
#endif
        }

        /// <summary>
        /// Used by CCW infrastructure code to return the target object from this pointer
        /// </summary>
        /// <returns>The target object pointed by this pointer</returns>
        public static object ThisPointerToTargetObject(IntPtr pUnk)
        {
            return ComCallableObject.GetTarget(pUnk);
        }

        [CLSCompliant(false)]
        public static object ComInterfaceToObject_NoUnboxing(
            IntPtr pComItf,
            RuntimeTypeHandle interfaceType)
        {
            return McgComHelpers.ComInterfaceToObjectInternal(
                pComItf,
                interfaceType,
                default(RuntimeTypeHandle),
                McgComHelpers.CreateComObjectFlags.SkipTypeResolutionAndUnboxing
            );
        }

        /// <summary>
        /// Shared CCW Interface To Object
        /// </summary>
        /// <param name="pComItf"></param>
        /// <param name="interfaceType"></param>
        /// <param name="classTypeInSignature"></param>
        /// <returns></returns>
        [CLSCompliant(false)]
        public static object ComInterfaceToObject(
            System.IntPtr pComItf,
            RuntimeTypeHandle interfaceType,
            RuntimeTypeHandle classTypeInSignature)
        {
#if ENABLE_MIN_WINRT
            if (interfaceType.Equals(typeof(object).TypeHandle))
            {
                return McgMarshal.IInspectableToObject(pComItf);
            }

            if (interfaceType.Equals(typeof(System.String).TypeHandle))
            {
                return McgMarshal.HStringToString(pComItf);
            }

            if (interfaceType.IsComClass())
            {
                RuntimeTypeHandle defaultInterface = interfaceType.GetDefaultInterface();
                Debug.Assert(!defaultInterface.IsNull());
                return ComInterfaceToObjectInternal(pComItf, defaultInterface, interfaceType);
            }
#endif
            return ComInterfaceToObjectInternal(
                pComItf,
                interfaceType,
                classTypeInSignature
            );
        }

        [CLSCompliant(false)]
        public static object ComInterfaceToObject(
            IntPtr pComItf,
            RuntimeTypeHandle interfaceType)
        {
            return ComInterfaceToObject(pComItf, interfaceType, default(RuntimeTypeHandle));
        }


        private static object ComInterfaceToObjectInternal(
            IntPtr pComItf,
            RuntimeTypeHandle interfaceType,
            RuntimeTypeHandle classTypeInSignature)
        {
            object result = McgComHelpers.ComInterfaceToObjectInternal(pComItf, interfaceType, classTypeInSignature, McgComHelpers.CreateComObjectFlags.None);

            //
            // Make sure the type we returned is actually of the right type
            // NOTE: Don't pass null to IsInstanceOfClass as it'll return false
            //
            if (!classTypeInSignature.IsNull() && result != null)
            {
                if (!InteropExtensions.IsInstanceOfClass(result, classTypeInSignature))
                    throw new InvalidCastException();
            }

            return result;
        }

        public static unsafe IntPtr ComQueryInterfaceNoThrow(IntPtr pComItf, ref Guid iid)
        {
            int hr = 0;
            return ComQueryInterfaceNoThrow(pComItf, ref iid, out hr);
        }

        public static unsafe IntPtr ComQueryInterfaceNoThrow(IntPtr pComItf, ref Guid iid, out int hr)
        {
            IntPtr pComIUnk;
            hr = ComQueryInterfaceWithHR(pComItf, ref iid, out pComIUnk);

            return pComIUnk;
        }

        internal static unsafe int ComQueryInterfaceWithHR(IntPtr pComItf, ref Guid iid, out IntPtr ppv)
        {
            IntPtr pComIUnk;
            int hr;

            fixed (Guid* unsafe_iid = &iid)
            {
                hr = CalliIntrinsics.StdCall__QueryInterface(((__com_IUnknown*)(void*)pComItf)->pVtable->
                                pfnQueryInterface,
                                pComItf,
                                new IntPtr(unsafe_iid),
                                new IntPtr(&pComIUnk));
            }

            if (hr != 0)
            {
                ppv = default(IntPtr);
            }
            else
            {
                ppv = pComIUnk;
            }

            return hr;
        }

        /// <summary>
        /// Helper function to copy vTable to native heap on CoreCLR.
        /// </summary>
        /// <typeparam name="T">Vtbl type</typeparam>
        /// <param name="pVtbl">static v-table field , always a valid pointer</param>
        /// <param name="pNativeVtbl">Pointer to Vtable on native heap on CoreCLR , on N it's an alias for pVtbl</param>
        public static unsafe IntPtr GetCCWVTableCopy(void* pVtbl, ref IntPtr pNativeVtbl, int size)
        {
            if (pNativeVtbl == default(IntPtr))
            {
#if CORECLR
                // On CoreCLR copy vTable to native heap , on N VTable is frozen.
                IntPtr  pv = Marshal.AllocHGlobal(size);

                int* pSrc = (int*)pVtbl;
                int* pDest = (int*)pv.ToPointer();
                int pSize = sizeof(int);

                // this should never happen , if a CCW is discarded we never get here.
                Debug.Assert(size >= pSize);
                for (int i = 0; i < size; i += pSize)
                {
                    *pDest++ = *pSrc++;
                }
                if (Interlocked.CompareExchange(ref pNativeVtbl, pv, default(IntPtr)) != default(IntPtr))
                {
                    // Another thread sneaked-in and updated pNativeVtbl , just use the update from other thread
                    Marshal.FreeHGlobal(pv);
                }
#else  // .NET NATIVE
                // Wrap it in an IntPtr
                pNativeVtbl = (IntPtr)pVtbl;
#endif // CORECLR
            }
            return pNativeVtbl;
        }

        [CLSCompliant(false)]
        public static IntPtr ObjectToComInterface(
            object obj,
            RuntimeTypeHandle typeHnd)
        {
#if ENABLE_MIN_WINRT
            if (typeHnd.Equals(typeof(object).TypeHandle))
            {
                return McgMarshal.ObjectToIInspectable(obj);
            }

            if (typeHnd.Equals(typeof(System.String).TypeHandle))
            {
                return McgMarshal.StringToHString((string)obj).handle;
            }

            if (typeHnd.IsComClass())
            {
                // This code path should be executed only for WinRT classes
                typeHnd = typeHnd.GetDefaultInterface();
                Debug.Assert(!typeHnd.IsNull());
            }
#endif
            return McgComHelpers.ObjectToComInterfaceInternal(
                obj,
                typeHnd
            );
        }

        public static IntPtr ObjectToIInspectable(Object obj)
        {
#if ENABLE_MIN_WINRT
            return ObjectToComInterface(obj, InternalTypes.IInspectable);
#else
            throw new PlatformNotSupportedException("ObjectToIInspectable");
#endif
        }

        // This is not a safe function to use for any funtion pointers that do not point
        // at a static function. This is due to the behavior of shared generics,
        // where instance function entry points may share the exact same address
        // but static functions are always represented in delegates with customized
        // stubs.
        private static bool DelegateTargetMethodEquals(Delegate del, IntPtr pfn)
        {
            RuntimeTypeHandle thDummy;
            return del.GetFunctionPointer(out thDummy) == pfn;
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        public static IntPtr DelegateToComInterface(Delegate del, RuntimeTypeHandle typeHnd)
        {
            if (del == null)
                return default(IntPtr);

            IntPtr stubFunctionAddr = typeHnd.GetDelegateInvokeStub();

            object targetObj;

            //
            // If the delegate points to the forward stub for the native delegate,
            // then we want the RCW associated with the native interface.  Otherwise,
            // this is a managed delegate, and we want the CCW associated with it.
            //
            if (DelegateTargetMethodEquals(del, stubFunctionAddr))
                targetObj = del.Target;
            else
                targetObj = del;

            return McgMarshal.ObjectToComInterface(targetObj, typeHnd);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        public static Delegate ComInterfaceToDelegate(IntPtr pComItf, RuntimeTypeHandle typeHnd)
        {
            if (pComItf == default(IntPtr))
                return null;

            object obj = ComInterfaceToObject(pComItf, typeHnd, /* classIndexInSignature */ default(RuntimeTypeHandle));

            //
            // If the object we got back was a managed delegate, then we're good.  Otherwise,
            // the object is an RCW for a native delegate, so we need to wrap it with a managed
            // delegate that invokes the correct stub.
            //
            Delegate del = obj as Delegate;
            if (del == null)
            {
                Debug.Assert(obj is __ComObject);
                IntPtr stubFunctionAddr = typeHnd.GetDelegateInvokeStub();

                del = InteropExtensions.CreateDelegate(
                    typeHnd,
                    stubFunctionAddr,
                    obj,
                    /*isStatic:*/ true,
                    /*isVirtual:*/ false,
                    /*isOpen:*/ false);
            }

            return del;
        }

        /// <summary>
        /// Marshal array of objects
        /// </summary>
        [MethodImplAttribute(MethodImplOptions.NoInlining)]
        unsafe public static void ObjectArrayToComInterfaceArray(uint len, System.IntPtr* dst, object[] src, RuntimeTypeHandle typeHnd)
        {
            for (uint i = 0; i < len; i++)
            {
                dst[i] = McgMarshal.ObjectToComInterface(src[i], typeHnd);
            }
        }

        /// <summary>
        /// Allocate native memory, and then marshal array of objects
        /// </summary>
        [MethodImplAttribute(MethodImplOptions.NoInlining)]
        unsafe public static System.IntPtr* ObjectArrayToComInterfaceArrayAlloc(object[] src, RuntimeTypeHandle typeHnd, out uint len)
        {
            System.IntPtr* dst = null;

            len = 0;

            if (src != null)
            {
                len = (uint)src.Length;

                dst = (System.IntPtr*)PInvokeMarshal.CoTaskMemAlloc((System.UIntPtr)(len * (sizeof(System.IntPtr))));

                for (uint i = 0; i < len; i++)
                {
                    dst[i] = McgMarshal.ObjectToComInterface(src[i], typeHnd);
                }
            }

            return dst;
        }

        /// <summary>
        /// Get outer IInspectable for managed object deriving from native scenario
        /// At this point the inner is not created yet - you need the outer first and pass it to the factory
        /// to create the inner
        /// </summary>
        [MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
        [CLSCompliant(false)]
        public static IntPtr GetOuterIInspectableForManagedObject(__ComObject managedObject)
        {
            ComCallableObject ccw = null;

            try
            {
                //
                // Create the CCW over the RCW
                // Note that they are actually both the same object
                // Base class = inner
                // Derived class = outer
                //
                ccw = new ComCallableObject(
                    managedObject,      // The target object              = managedObject
                    managedObject       // The inner RCW (as __ComObject) = managedObject
                );

                //
                // Retrieve the outer IInspectable
                // Pass skipInterfaceCheck = true to avoid redundant checks
                //
                return ccw.GetComInterfaceForType_NoCheck(InternalTypes.IInspectable, ref Interop.COM.IID_IInspectable);
            }
            finally
            {
                //
                // Free the extra ref count initialized by __native_ccw.Init (to protect the CCW from being collected)
                //
                if (ccw != null)
                    ccw.Release();
            }
        }

        [CLSCompliant(false)]
        public static unsafe IntPtr ManagedObjectToComInterface(Object obj, RuntimeTypeHandle interfaceType)
        {
            return McgComHelpers.ManagedObjectToComInterface(obj, interfaceType);
        }

        public static unsafe object IInspectableToObject(IntPtr pComItf)
        {
#if ENABLE_WINRT
            return ComInterfaceToObject(pComItf, InternalTypes.IInspectable);
#else
            throw new PlatformNotSupportedException("IInspectableToObject");
#endif
        }

        public static unsafe IntPtr CoCreateInstanceEx(Guid clsid, string server)
        {
#if ENABLE_WINRT
            Interop.COM.MULTI_QI results;
            IntPtr pResults = new IntPtr(&results);
            fixed (Guid* pIID = &Interop.COM.IID_IUnknown)
            {
                Guid* pClsid = &clsid;

                results.pIID = new IntPtr(pIID);
                results.pItf = IntPtr.Zero;
                results.hr = 0;
                int hr;
                            
                // if server name is specified, do remote server activation
                if (!String.IsNullOrEmpty(server))
                {
                    Interop.COM.COSERVERINFO serverInfo;
                    fixed (char* pName = server)
                    {
                        serverInfo.Name = new IntPtr(pName);
                        IntPtr pServerInfo = new IntPtr(&serverInfo);

                        hr = ExternalInterop.CoCreateInstanceFromApp(pClsid, IntPtr.Zero, (int)Interop.COM.CLSCTX.CLSCTX_REMOTE_SERVER, pServerInfo, 1, pResults);
                    }
            
                }
                else
                {
                   hr = ExternalInterop.CoCreateInstanceFromApp(pClsid, IntPtr.Zero, (int)Interop.COM.CLSCTX.CLSCTX_SERVER, IntPtr.Zero, 1, pResults);
                }

                if (hr < 0)
                {
                    throw McgMarshal.GetExceptionForHR(hr, /*isWinRTScenario = */ false);
                }
                if (results.hr < 0)
                {
                    throw McgMarshal.GetExceptionForHR(results.hr, /* isWinRTScenario = */ false);
                }
            return results.pItf;
            }
#else
            throw new PlatformNotSupportedException("CoCreateInstanceEx");
#endif

        }

        public static unsafe IntPtr CoCreateInstanceEx(Guid clsid)
        {
            return CoCreateInstanceEx(clsid, string.Empty);
        }
        #endregion

        #region Testing

        /// <summary>
        /// Internal-only method to allow testing of apartment teardown code
        /// </summary>
        public static void ReleaseRCWsInCurrentApartment()
        {
            ContextEntry.RemoveCurrentContext();
        }

        /// <summary>
        /// Used by detecting leaks
        /// Used in prefast MCG only
        /// </summary>
        public static int GetTotalComObjectCount()
        {
            return ComObjectCache.s_comObjectMap.Count;
        }

        /// <summary>
        /// Used by detecting and dumping leaks
        /// Used in prefast MCG only
        /// </summary>
        public static IEnumerable<__ComObject> GetAllComObjects()
        {
            List<__ComObject> list = new List<__ComObject>();
            for (int i = 0; i < ComObjectCache.s_comObjectMap.GetMaxCount(); ++i)
            {
                IntPtr pHandle = default(IntPtr);
                if (ComObjectCache.s_comObjectMap.GetValue(i, ref pHandle) && (pHandle != default(IntPtr)))
                {
                    GCHandle handle = GCHandle.FromIntPtr(pHandle);
                    list.Add(InteropExtensions.UncheckedCast<__ComObject>(handle.Target));
                }
            }

            return list;
        }

#endregion

        /// <summary>
        /// This method propagate the exception being thrown.
        /// 1. On Windows8+, WinRT scenarios we do the following.
        ///      a. Check whether the exception has any IRestrictedErrorInfo associated with it.
        ///          If so, it means that this exception was actually caused by a native exception in which case we do simply use the same
        ///              message and stacktrace.
        ///      b.  If not, this is actually a managed exception and in this case we RoOriginateLanguageException with the msg, hresult and the IErrorInfo
        ///          associated with the managed exception. This helps us to retrieve the same exception in case it comes back to native.
        /// 2. On win8 and for classic COM scenarios.
        ///     a. This method should not be called
        /// </summary>
        /// <param name="ex"></param>
        [MethodImpl(MethodImplOptions.NoInlining)]
        public static bool PropagateException(Exception ex)
        {
#if ENABLE_WINRT
            return ExceptionHelpers.PropagateException(ex);
#else
            // TODO : ExceptionHelpers should be platform specific , move it to
            // seperate source files
            return true;
#endif
        }

        /// <summary>
        /// This method returns HR for the exception being thrown.
        /// 1. On Windows8+, WinRT scenarios 
        ///     The work to propagate the exception should have already performed in the exception filter
        ///     by calling PropagateException()
        /// 2. On win8 and for classic COM scenarios.
        ///     a. We create IErrorInfo for the given Exception object and SetErrorInfo with the given IErrorInfo.
        /// </summary>
        /// <param name="ex"></param>
        [MethodImpl(MethodImplOptions.NoInlining)]
        public static int GetHRForExceptionWinRT(Exception ex)
        {
#if ENABLE_WINRT
            return ExceptionHelpers.GetHRForExceptionWithErrorPropagationNoThrow(ex, true);
#else
            // TODO : ExceptionHelpers should be platform specific , move it to
            // seperate source files
            return 0;
            //return Marshal.GetHRForException(ex);
#endif
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        public static int GetHRForException(Exception ex)
        {
#if ENABLE_WINRT
            return ExceptionHelpers.GetHRForExceptionWithErrorPropagationNoThrow(ex, false);
#else
            return ex.HResult;
#endif
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        public static void ThrowOnExternalCallFailed(int hr, System.RuntimeTypeHandle typeHnd)
        {
            bool isWinRTScenario
#if ENABLE_WINRT
            = typeHnd.IsSupportIInspectable();
#else
            = false;
#endif
            throw McgMarshal.GetExceptionForHR(hr, isWinRTScenario);
        }

        /// <summary>
        /// This method returns a new Exception object given the HR value.
        /// </summary>
        /// <param name="hr"></param>
        /// <param name="isWinRTScenario"></param>
        public static Exception GetExceptionForHR(int hr, bool isWinRTScenario)
        {
#if ENABLE_WINRT
            return ExceptionHelpers.GetExceptionForHRInternalNoThrow(hr, isWinRTScenario, !isWinRTScenario);
#elif CORECLR
            return Marshal.GetExceptionForHR(hr);
#else
            // TODO: Map HR to exeption even without COM interop support?
            return new COMException(hr);
#endif
        }

#region Shared templates
#if ENABLE_MIN_WINRT
        public static void CleanupNative<T>(IntPtr pObject)
        {
            if (typeof(T) == typeof(string))
            {
                global::System.Runtime.InteropServices.McgMarshal.FreeHString(pObject);
            }
            else
            {
                global::System.Runtime.InteropServices.McgMarshal.ComSafeRelease(pObject);
            }
        }
#endif
#endregion

#if ENABLE_MIN_WINRT
        [MethodImpl(MethodImplOptions.NoInlining)]
        public static unsafe IntPtr ActivateInstance(string typeName)
        {
            __ComObject target = McgMarshal.GetActivationFactory(
                typeName,
                InternalTypes.IActivationFactoryInternal
            );

            IntPtr pIActivationFactoryInternalItf = target.QueryInterface_NoAddRef_Internal(
                InternalTypes.IActivationFactoryInternal,
                /* cacheOnly= */ false,
                /* throwOnQueryInterfaceFailure= */ true
            );

            __com_IActivationFactoryInternal* pIActivationFactoryInternal = (__com_IActivationFactoryInternal*)pIActivationFactoryInternalItf;

            IntPtr pResult = default(IntPtr);

            int hr = CalliIntrinsics.StdCall__int(
                pIActivationFactoryInternal->pVtable->pfnActivateInstance,
                pIActivationFactoryInternal,
                &pResult
            );

            GC.KeepAlive(target);

            if (hr < 0)
            {
                throw McgMarshal.GetExceptionForHR(hr, /* isWinRTScenario = */ true);
            }

            return pResult;
        }
#endif

        [MethodImpl(MethodImplOptions.NoInlining)]
        public static IntPtr GetInterface(
            __ComObject obj,
            RuntimeTypeHandle typeHnd)
        {
            return obj.QueryInterface_NoAddRef_Internal(
                typeHnd);
        }

        [MethodImplAttribute(MethodImplOptions.NoInlining)]
        public static object GetDynamicAdapter(__ComObject obj, RuntimeTypeHandle requestedType, RuntimeTypeHandle existingType)
        {
            return obj.GetDynamicAdapter(requestedType, existingType);
        }

        [MethodImplAttribute(MethodImplOptions.NoInlining)]
        public static object GetDynamicAdapter(__ComObject obj, RuntimeTypeHandle requestedType)
        {
            return obj.GetDynamicAdapter(requestedType, default(RuntimeTypeHandle));
        }

#region "PInvoke Delegate"

        public static IntPtr GetStubForPInvokeDelegate(RuntimeTypeHandle delegateType, Delegate dele)
        {
#if CORECLR
             throw new NotSupportedException();
#else
            return PInvokeMarshal.GetFunctionPointerForDelegate(dele);
#endif
        }

        /// <summary>
        /// Retrieve the corresponding P/invoke instance from the stub
        /// </summary>
        public static Delegate GetPInvokeDelegateForStub(IntPtr pStub, RuntimeTypeHandle delegateType)
        {
#if CORECLR
            if (pStub == IntPtr.Zero)
                return null;

            McgPInvokeDelegateData pInvokeDelegateData;
            if (!McgModuleManager.GetPInvokeDelegateData(delegateType, out pInvokeDelegateData))
            {
                return null;
            }

            return CalliIntrinsics.Call__Delegate(
                pInvokeDelegateData.ForwardDelegateCreationStub,
                pStub
            );
#else
            return PInvokeMarshal.GetDelegateForFunctionPointer(pStub, delegateType);
#endif
        }

        /// <summary>
        /// Retrieves the function pointer for the current open static delegate that is being called
        /// </summary>
        public static IntPtr GetCurrentCalleeOpenStaticDelegateFunctionPointer()
        {
#if !RHTESTCL && PROJECTN
            return PInvokeMarshal.GetCurrentCalleeOpenStaticDelegateFunctionPointer();
#else
            throw new NotSupportedException();
#endif
        }

        /// <summary>
        /// Retrieves the current delegate that is being called
        /// </summary>
        public static T GetCurrentCalleeDelegate<T>() where T : class // constraint can't be System.Delegate
        {
#if !RHTESTCL && PROJECTN
            return PInvokeMarshal.GetCurrentCalleeDelegate<T>();
#else
            throw new NotSupportedException();
#endif
        }
#endregion
    }

    /// <summary>
    /// McgMarshal helpers exposed to be used by MCG
    /// </summary>
    public static partial class McgMarshal
    {
        public static object UnboxIfBoxed(object target)
        {
            return UnboxIfBoxed(target, null);
        }

        public static object UnboxIfBoxed(object target, string className)
        {
            //
            // If it is a managed wrapper, unbox it
            //
            object unboxedObj = McgComHelpers.UnboxManagedWrapperIfBoxed(target);
            if (unboxedObj != target)
                return unboxedObj;

            if (className == null)
                className = System.Runtime.InteropServices.McgComHelpers.GetRuntimeClassName(target);

            if (!String.IsNullOrEmpty(className))
            {
                IntPtr unboxingStub;
                if (McgModuleManager.TryGetUnboxingStub(className, out unboxingStub))
                {
                    object ret = CalliIntrinsics.Call<object>(unboxingStub, target);

                    if (ret != null)
                        return ret;
                }
#if ENABLE_WINRT
                else if(McgModuleManager.UseDynamicInterop)
                {
                    BoxingInterfaceKind boxingInterfaceKind;
                    RuntimeTypeHandle[] genericTypeArgument;
                    if (DynamicInteropBoxingHelpers.TryGetBoxingArgumentTypeHandleFromString(className, out boxingInterfaceKind, out genericTypeArgument))
                    {
                        Debug.Assert(target is __ComObject);
                        return DynamicInteropBoxingHelpers.Unboxing(boxingInterfaceKind, genericTypeArgument, target);
                    }
                }
#endif
            }
            return null;
        }

        internal static object BoxIfBoxable(object target)
        {
            return BoxIfBoxable(target, default(RuntimeTypeHandle));
        }

        /// <summary>
        /// Given a boxed value type, return a wrapper supports the IReference interface
        /// </summary>
        /// <param name="typeHandleOverride">
        /// You might want to specify how to box this. For example, any object[] derived array could
        /// potentially boxed as object[] if everything else fails
        /// </param>
        internal static object BoxIfBoxable(object target, RuntimeTypeHandle typeHandleOverride)
        {
            RuntimeTypeHandle expectedTypeHandle = typeHandleOverride;
            if (expectedTypeHandle.Equals(default(RuntimeTypeHandle)))
                expectedTypeHandle = target.GetTypeHandle();

            RuntimeTypeHandle boxingWrapperType;
            IntPtr boxingStub;
            int boxingPropertyType;
            if (McgModuleManager.TryGetBoxingWrapperType(expectedTypeHandle, target, out boxingWrapperType, out boxingPropertyType, out boxingStub))
            {
                if (!boxingWrapperType.IsInvalid())
                {
                    //
                    // IReference<T> / IReferenceArray<T> / IKeyValuePair<K, V>
                    // All these scenarios require a managed wrapper
                    //

                    // Allocate the object
                    object refImplType = InteropExtensions.RuntimeNewObject(boxingWrapperType);

                    if (boxingPropertyType >= 0)
                    {
                        Debug.Assert(refImplType is BoxedValue);

                        BoxedValue boxed = InteropExtensions.UncheckedCast<BoxedValue>(refImplType);

                        // Call ReferenceImpl<T>.Initialize(obj, type);
                        boxed.Initialize(target, boxingPropertyType);
                    }
                    else
                    {
                        Debug.Assert(refImplType is BoxedKeyValuePair);

                        BoxedKeyValuePair boxed = InteropExtensions.UncheckedCast<BoxedKeyValuePair>(refImplType);

                        // IKeyValuePair<,>,   call CLRIKeyValuePairImpl<K,V>.Initialize(object obj);
                        // IKeyValuePair<,>[], call CLRIKeyValuePairArrayImpl<K,V>.Initialize(object obj);
                        refImplType = boxed.Initialize(target);
                    }

                    return refImplType;
                }
                else
                {
                    //
                    // General boxing for projected types, such as System.Uri
                    //
                    return CalliIntrinsics.Call<object>(boxingStub, target);
                }
            }

            return null;
        }
    }
}