1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
5 /*=============================================================================
9 ** Purpose: This class contains methods that are mainly used to marshal
10 ** between unmanaged and managed types.
13 =============================================================================*/
15 namespace System.Runtime.InteropServices
19 using System.Collections.Generic;
20 using System.Reflection;
21 using System.Reflection.Emit;
22 using System.Security;
24 using System.Threading;
25 using System.Runtime.CompilerServices;
26 using System.Globalization;
27 using System.Runtime.ConstrainedExecution;
28 using System.Runtime.Versioning;
29 using Win32Native = Microsoft.Win32.Win32Native;
30 using Microsoft.Win32.SafeHandles;
31 using System.Diagnostics;
32 using System.Runtime.InteropServices.ComTypes;
33 using System.StubHelpers;
35 public enum CustomQueryInterfaceMode
41 //========================================================================
42 // All public methods, including PInvoke, are protected with linkchecks.
43 // Remove the default demands for all PInvoke methods with this global
44 // declaration on the class.
45 //========================================================================
47 public static partial class Marshal
49 //====================================================================
50 // Defines used inside the Marshal class.
51 //====================================================================
52 private const int LMEM_FIXED = 0;
53 private const int LMEM_MOVEABLE = 2;
55 private const long HIWORDMASK = unchecked((long)0xffffffffffff0000L);
57 #if FEATURE_COMINTEROP
58 private static Guid IID_IUnknown = new Guid("00000000-0000-0000-C000-000000000046");
59 #endif //FEATURE_COMINTEROP
61 // Win32 has the concept of Atoms, where a pointer can either be a pointer
62 // or an int. If it's less than 64K, this is guaranteed to NOT be a
63 // pointer since the bottom 64K bytes are reserved in a process' page table.
64 // We should be careful about deallocating this stuff. Extracted to
65 // a function to avoid C# problems with lack of support for IntPtr.
66 // We have 2 of these methods for slightly different semantics for NULL.
67 private static bool IsWin32Atom(IntPtr ptr)
72 long lPtr = (long)ptr;
73 return 0 == (lPtr & HIWORDMASK);
77 private static bool IsNotWin32Atom(IntPtr ptr)
82 long lPtr = (long)ptr;
83 return 0 != (lPtr & HIWORDMASK);
87 //====================================================================
88 // The default character size for the system. This is always 2 because
89 // the framework only runs on UTF-16 systems.
90 //====================================================================
91 public static readonly int SystemDefaultCharSize = 2;
93 //====================================================================
94 // The max DBCS character size for the system.
95 //====================================================================
96 public static readonly int SystemMaxDBCSCharSize = GetSystemMaxDBCSCharSize();
99 //====================================================================
100 // The name, title and description of the assembly that will contain
101 // the dynamically generated interop types.
102 //====================================================================
103 private const String s_strConvertedTypeInfoAssemblyName = "InteropDynamicTypes";
104 private const String s_strConvertedTypeInfoAssemblyTitle = "Interop Dynamic Types";
105 private const String s_strConvertedTypeInfoAssemblyDesc = "Type dynamically generated from ITypeInfo's";
106 private const String s_strConvertedTypeInfoNameSpace = "InteropDynamicTypes";
109 //====================================================================
110 // Helper method to retrieve the system's maximum DBCS character size.
111 //====================================================================
112 [MethodImplAttribute(MethodImplOptions.InternalCall)]
113 private static extern int GetSystemMaxDBCSCharSize();
115 public static unsafe String PtrToStringAnsi(IntPtr ptr)
117 if (IntPtr.Zero == ptr)
121 else if (IsWin32Atom(ptr))
127 int nb = Win32Native.lstrlenA(ptr);
134 return new String((sbyte*)ptr);
139 public static unsafe String PtrToStringAnsi(IntPtr ptr, int len)
141 if (ptr == IntPtr.Zero)
142 throw new ArgumentNullException(nameof(ptr));
144 throw new ArgumentException(null, nameof(len));
146 return new String((sbyte*)ptr, 0, len);
149 public static unsafe String PtrToStringUni(IntPtr ptr, int len)
151 if (ptr == IntPtr.Zero)
152 throw new ArgumentNullException(nameof(ptr));
154 throw new ArgumentException(null, nameof(len));
156 return new String((char*)ptr, 0, len);
159 public static String PtrToStringAuto(IntPtr ptr, int len)
161 // Ansi platforms are no longer supported
162 return PtrToStringUni(ptr, len);
165 public static unsafe String PtrToStringUni(IntPtr ptr)
167 if (IntPtr.Zero == ptr)
171 else if (IsWin32Atom(ptr))
177 return new String((char*)ptr);
181 public static String PtrToStringAuto(IntPtr ptr)
183 // Ansi platforms are no longer supported
184 return PtrToStringUni(ptr);
187 public static unsafe String PtrToStringUTF8(IntPtr ptr)
189 if (IntPtr.Zero == ptr)
195 int nbBytes = System.StubHelpers.StubHelpers.strlen((sbyte*)ptr.ToPointer());
196 return PtrToStringUTF8(ptr, nbBytes);
200 public static unsafe String PtrToStringUTF8(IntPtr ptr, int byteLen)
204 throw new ArgumentOutOfRangeException(nameof(byteLen), SR.ArgumentOutOfRange_NeedNonNegNum);
206 else if (IntPtr.Zero == ptr)
210 else if (IsWin32Atom(ptr))
214 else if (byteLen == 0)
220 byte* pByte = (byte*)ptr.ToPointer();
221 return Encoding.UTF8.GetString(pByte, byteLen);
225 //====================================================================
227 //====================================================================
228 public static int SizeOf(Object structure)
230 if (structure == null)
231 throw new ArgumentNullException(nameof(structure));
232 // we never had a check for generics here
234 return SizeOfHelper(structure.GetType(), true);
237 public static int SizeOf<T>(T structure)
239 return SizeOf((object)structure);
242 public static int SizeOf(Type t)
245 throw new ArgumentNullException(nameof(t));
246 if (!(t is RuntimeType))
247 throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(t));
249 throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t));
251 return SizeOfHelper(t, true);
254 public static int SizeOf<T>()
256 return SizeOf(typeof(T));
259 [MethodImplAttribute(MethodImplOptions.InternalCall)]
260 internal static extern int SizeOfHelper(Type t, bool throwIfNotMarshalable);
262 //====================================================================
264 //====================================================================
265 public static IntPtr OffsetOf(Type t, String fieldName)
268 throw new ArgumentNullException(nameof(t));
270 FieldInfo f = t.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
272 throw new ArgumentException(SR.Format(SR.Argument_OffsetOfFieldNotFound, t.FullName), nameof(fieldName));
273 RtFieldInfo rtField = f as RtFieldInfo;
275 throw new ArgumentException(SR.Argument_MustBeRuntimeFieldInfo, nameof(fieldName));
277 return OffsetOfHelper(rtField);
279 public static IntPtr OffsetOf<T>(string fieldName)
281 return OffsetOf(typeof(T), fieldName);
284 [MethodImplAttribute(MethodImplOptions.InternalCall)]
285 private static extern IntPtr OffsetOfHelper(IRuntimeFieldInfo f);
287 //====================================================================
288 // UnsafeAddrOfPinnedArrayElement()
290 // IMPORTANT NOTICE: This method does not do any verification on the
291 // array. It must be used with EXTREME CAUTION since passing in
292 // an array that is not pinned or in the fixed heap can cause
293 // unexpected results !
294 //====================================================================
295 [MethodImplAttribute(MethodImplOptions.InternalCall)]
296 public static extern IntPtr UnsafeAddrOfPinnedArrayElement(Array arr, int index);
298 public static IntPtr UnsafeAddrOfPinnedArrayElement<T>(T[] arr, int index)
300 return UnsafeAddrOfPinnedArrayElement((Array)arr, index);
303 //====================================================================
304 // Copy blocks from CLR arrays to native memory.
305 //====================================================================
306 public static void Copy(int[] source, int startIndex, IntPtr destination, int length)
308 CopyToNative(source, startIndex, destination, length);
310 public static void Copy(char[] source, int startIndex, IntPtr destination, int length)
312 CopyToNative(source, startIndex, destination, length);
314 public static void Copy(short[] source, int startIndex, IntPtr destination, int length)
316 CopyToNative(source, startIndex, destination, length);
318 public static void Copy(long[] source, int startIndex, IntPtr destination, int length)
320 CopyToNative(source, startIndex, destination, length);
322 public static void Copy(float[] source, int startIndex, IntPtr destination, int length)
324 CopyToNative(source, startIndex, destination, length);
326 public static void Copy(double[] source, int startIndex, IntPtr destination, int length)
328 CopyToNative(source, startIndex, destination, length);
330 public static void Copy(byte[] source, int startIndex, IntPtr destination, int length)
332 CopyToNative(source, startIndex, destination, length);
334 public static void Copy(IntPtr[] source, int startIndex, IntPtr destination, int length)
336 CopyToNative(source, startIndex, destination, length);
338 [MethodImplAttribute(MethodImplOptions.InternalCall)]
339 private static extern void CopyToNative(Object source, int startIndex, IntPtr destination, int length);
341 //====================================================================
342 // Copy blocks from native memory to CLR arrays
343 //====================================================================
344 public static void Copy(IntPtr source, int[] destination, int startIndex, int length)
346 CopyToManaged(source, destination, startIndex, length);
348 public static void Copy(IntPtr source, char[] destination, int startIndex, int length)
350 CopyToManaged(source, destination, startIndex, length);
352 public static void Copy(IntPtr source, short[] destination, int startIndex, int length)
354 CopyToManaged(source, destination, startIndex, length);
356 public static void Copy(IntPtr source, long[] destination, int startIndex, int length)
358 CopyToManaged(source, destination, startIndex, length);
360 public static void Copy(IntPtr source, float[] destination, int startIndex, int length)
362 CopyToManaged(source, destination, startIndex, length);
364 public static void Copy(IntPtr source, double[] destination, int startIndex, int length)
366 CopyToManaged(source, destination, startIndex, length);
368 public static void Copy(IntPtr source, byte[] destination, int startIndex, int length)
370 CopyToManaged(source, destination, startIndex, length);
372 public static void Copy(IntPtr source, IntPtr[] destination, int startIndex, int length)
374 CopyToManaged(source, destination, startIndex, length);
376 [MethodImplAttribute(MethodImplOptions.InternalCall)]
377 private static extern void CopyToManaged(IntPtr source, Object destination, int startIndex, int length);
379 //====================================================================
381 //====================================================================
382 public static byte ReadByte(Object ptr, int ofs)
384 return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => Marshal.ReadByte(nativeHome, offset));
387 public static unsafe byte ReadByte(IntPtr ptr, int ofs)
391 byte* addr = (byte*)ptr + ofs;
394 catch (NullReferenceException)
396 // this method is documented to throw AccessViolationException on any AV
397 throw new AccessViolationException();
401 public static byte ReadByte(IntPtr ptr)
403 return ReadByte(ptr, 0);
406 public static short ReadInt16(Object ptr, int ofs)
408 return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => Marshal.ReadInt16(nativeHome, offset));
411 public static unsafe short ReadInt16(IntPtr ptr, int ofs)
415 byte* addr = (byte*)ptr + ofs;
416 if ((unchecked((int)addr) & 0x1) == 0)
419 return *((short*)addr);
425 byte* valPtr = (byte*)&val;
431 catch (NullReferenceException)
433 // this method is documented to throw AccessViolationException on any AV
434 throw new AccessViolationException();
438 public static short ReadInt16(IntPtr ptr)
440 return ReadInt16(ptr, 0);
443 public static int ReadInt32(object ptr, int ofs)
445 return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => Marshal.ReadInt32(nativeHome, offset));
448 public static unsafe int ReadInt32(IntPtr ptr, int ofs)
452 byte* addr = (byte*)ptr + ofs;
453 if ((unchecked((int)addr) & 0x3) == 0)
456 return *((int*)addr);
462 byte* valPtr = (byte*)&val;
470 catch (NullReferenceException)
472 // this method is documented to throw AccessViolationException on any AV
473 throw new AccessViolationException();
477 public static int ReadInt32(IntPtr ptr)
479 return ReadInt32(ptr, 0);
482 public static IntPtr ReadIntPtr(Object ptr, int ofs)
485 return (IntPtr)ReadInt64(ptr, ofs);
487 return (IntPtr) ReadInt32(ptr, ofs);
491 public static IntPtr ReadIntPtr(IntPtr ptr, int ofs)
494 return (IntPtr)ReadInt64(ptr, ofs);
496 return (IntPtr) ReadInt32(ptr, ofs);
500 public static IntPtr ReadIntPtr(IntPtr ptr)
503 return (IntPtr)ReadInt64(ptr, 0);
505 return (IntPtr) ReadInt32(ptr, 0);
509 public static long ReadInt64([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs)
511 return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => Marshal.ReadInt64(nativeHome, offset));
514 public static unsafe long ReadInt64(IntPtr ptr, int ofs)
518 byte* addr = (byte*)ptr + ofs;
519 if ((unchecked((int)addr) & 0x7) == 0)
522 return *((long*)addr);
528 byte* valPtr = (byte*)&val;
540 catch (NullReferenceException)
542 // this method is documented to throw AccessViolationException on any AV
543 throw new AccessViolationException();
547 public static long ReadInt64(IntPtr ptr)
549 return ReadInt64(ptr, 0);
552 //====================================================================
553 // Read value from marshaled object (marshaled using AsAny)
554 // It's quite slow and can return back dangling pointers
555 // It's only there for backcompact
556 // I don't think we should spend time optimizing it
557 // People should really call the IntPtr overload instead
558 //====================================================================
559 private static unsafe T ReadValueSlow<T>(object ptr, int ofs, Func<IntPtr, int, T> readValueHelper)
561 // We AV on desktop if passing NULL. So this is technically a breaking change but is an improvement
563 throw new ArgumentNullException(nameof(ptr));
566 (int)AsAnyMarshaler.AsAnyFlags.In |
567 (int)AsAnyMarshaler.AsAnyFlags.IsAnsi |
568 (int)AsAnyMarshaler.AsAnyFlags.IsBestFit;
570 MngdNativeArrayMarshaler.MarshalerState nativeArrayMarshalerState = new MngdNativeArrayMarshaler.MarshalerState();
571 AsAnyMarshaler marshaler = new AsAnyMarshaler(new IntPtr(&nativeArrayMarshalerState));
573 IntPtr pNativeHome = IntPtr.Zero;
577 pNativeHome = marshaler.ConvertToNative(ptr, dwFlags);
578 return readValueHelper(pNativeHome, ofs);
582 marshaler.ClearNative(pNativeHome);
588 //====================================================================
590 //====================================================================
591 public static unsafe void WriteByte(IntPtr ptr, int ofs, byte val)
595 byte* addr = (byte*)ptr + ofs;
598 catch (NullReferenceException)
600 // this method is documented to throw AccessViolationException on any AV
601 throw new AccessViolationException();
605 public static void WriteByte(Object ptr, int ofs, byte val)
607 WriteValueSlow(ptr, ofs, val, (IntPtr nativeHome, int offset, byte value) => Marshal.WriteByte(nativeHome, offset, value));
610 public static void WriteByte(IntPtr ptr, byte val)
612 WriteByte(ptr, 0, val);
615 public static unsafe void WriteInt16(IntPtr ptr, int ofs, short val)
619 byte* addr = (byte*)ptr + ofs;
620 if ((unchecked((int)addr) & 0x1) == 0)
623 *((short*)addr) = val;
628 byte* valPtr = (byte*)&val;
633 catch (NullReferenceException)
635 // this method is documented to throw AccessViolationException on any AV
636 throw new AccessViolationException();
640 public static void WriteInt16(Object ptr, int ofs, short val)
642 WriteValueSlow(ptr, ofs, val, (IntPtr nativeHome, int offset, short value) => Marshal.WriteInt16(nativeHome, offset, value));
645 public static void WriteInt16(IntPtr ptr, short val)
647 WriteInt16(ptr, 0, val);
650 public static void WriteInt16(IntPtr ptr, int ofs, char val)
652 WriteInt16(ptr, ofs, (short)val);
655 public static void WriteInt16([In, Out]Object ptr, int ofs, char val)
657 WriteInt16(ptr, ofs, (short)val);
660 public static void WriteInt16(IntPtr ptr, char val)
662 WriteInt16(ptr, 0, (short)val);
665 public static unsafe void WriteInt32(IntPtr ptr, int ofs, int val)
669 byte* addr = (byte*)ptr + ofs;
670 if ((unchecked((int)addr) & 0x3) == 0)
678 byte* valPtr = (byte*)&val;
685 catch (NullReferenceException)
687 // this method is documented to throw AccessViolationException on any AV
688 throw new AccessViolationException();
692 public static void WriteInt32(Object ptr, int ofs, int val)
694 WriteValueSlow(ptr, ofs, val, (IntPtr nativeHome, int offset, int value) => Marshal.WriteInt32(nativeHome, offset, value));
697 public static void WriteInt32(IntPtr ptr, int val)
699 WriteInt32(ptr, 0, val);
702 public static void WriteIntPtr(IntPtr ptr, int ofs, IntPtr val)
705 WriteInt64(ptr, ofs, (long)val);
707 WriteInt32(ptr, ofs, (int)val);
711 public static void WriteIntPtr(Object ptr, int ofs, IntPtr val)
714 WriteInt64(ptr, ofs, (long)val);
716 WriteInt32(ptr, ofs, (int)val);
720 public static void WriteIntPtr(IntPtr ptr, IntPtr val)
723 WriteInt64(ptr, 0, (long)val);
725 WriteInt32(ptr, 0, (int)val);
729 public static unsafe void WriteInt64(IntPtr ptr, int ofs, long val)
733 byte* addr = (byte*)ptr + ofs;
734 if ((unchecked((int)addr) & 0x7) == 0)
737 *((long*)addr) = val;
742 byte* valPtr = (byte*)&val;
753 catch (NullReferenceException)
755 // this method is documented to throw AccessViolationException on any AV
756 throw new AccessViolationException();
760 public static void WriteInt64(Object ptr, int ofs, long val)
762 WriteValueSlow(ptr, ofs, val, (IntPtr nativeHome, int offset, long value) => Marshal.WriteInt64(nativeHome, offset, value));
765 public static void WriteInt64(IntPtr ptr, long val)
767 WriteInt64(ptr, 0, val);
770 //====================================================================
771 // Write value into marshaled object (marshaled using AsAny) and
772 // propagate the value back
773 // It's quite slow and is only there for backcompact
774 // I don't think we should spend time optimizing it
775 // People should really call the IntPtr overload instead
776 //====================================================================
777 private static unsafe void WriteValueSlow<T>(object ptr, int ofs, T val, Action<IntPtr, int, T> writeValueHelper)
779 // We AV on desktop if passing NULL. So this is technically a breaking change but is an improvement
781 throw new ArgumentNullException(nameof(ptr));
784 (int)AsAnyMarshaler.AsAnyFlags.In |
785 (int)AsAnyMarshaler.AsAnyFlags.Out |
786 (int)AsAnyMarshaler.AsAnyFlags.IsAnsi |
787 (int)AsAnyMarshaler.AsAnyFlags.IsBestFit;
789 MngdNativeArrayMarshaler.MarshalerState nativeArrayMarshalerState = new MngdNativeArrayMarshaler.MarshalerState();
790 AsAnyMarshaler marshaler = new AsAnyMarshaler(new IntPtr(&nativeArrayMarshalerState));
792 IntPtr pNativeHome = IntPtr.Zero;
796 pNativeHome = marshaler.ConvertToNative(ptr, dwFlags);
797 writeValueHelper(pNativeHome, ofs, val);
798 marshaler.ConvertToManaged(ptr, pNativeHome);
802 marshaler.ClearNative(pNativeHome);
806 //====================================================================
808 //====================================================================
809 [MethodImplAttribute(MethodImplOptions.InternalCall)]
810 public static extern int GetLastWin32Error();
813 //====================================================================
815 //====================================================================
816 [MethodImplAttribute(MethodImplOptions.InternalCall)]
817 internal static extern void SetLastWin32Error(int error);
820 //====================================================================
821 // GetHRForLastWin32Error
822 //====================================================================
823 public static int GetHRForLastWin32Error()
825 int dwLastError = GetLastWin32Error();
826 if ((dwLastError & 0x80000000) == 0x80000000)
829 return (dwLastError & 0x0000FFFF) | unchecked((int)0x80070000);
833 //====================================================================
835 //====================================================================
836 public static void Prelink(MethodInfo m)
839 throw new ArgumentNullException(nameof(m));
841 RuntimeMethodInfo rmi = m as RuntimeMethodInfo;
844 throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo);
846 InternalPrelink(rmi);
849 [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
850 private static extern void InternalPrelink(IRuntimeMethodInfo m);
852 public static void PrelinkAll(Type c)
855 throw new ArgumentNullException(nameof(c));
857 MethodInfo[] mi = c.GetMethods();
860 for (int i = 0; i < mi.Length; i++)
867 [MethodImplAttribute(MethodImplOptions.InternalCall)]
868 public static extern /* struct _EXCEPTION_POINTERS* */ IntPtr GetExceptionPointers();
870 [MethodImplAttribute(MethodImplOptions.InternalCall)]
871 public static extern int GetExceptionCode();
874 //====================================================================
875 // Marshals data from a structure class to a native memory block.
876 // If the structure contains pointers to allocated blocks and
877 // "fDeleteOld" is true, this routine will call DestroyStructure() first.
878 //====================================================================
879 [MethodImplAttribute(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
880 public static extern void StructureToPtr(Object structure, IntPtr ptr, bool fDeleteOld);
882 public static void StructureToPtr<T>(T structure, IntPtr ptr, bool fDeleteOld)
884 StructureToPtr((object)structure, ptr, fDeleteOld);
887 //====================================================================
888 // Marshals data from a native memory block to a preallocated structure class.
889 //====================================================================
890 public static void PtrToStructure(IntPtr ptr, Object structure)
892 PtrToStructureHelper(ptr, structure, false);
895 public static void PtrToStructure<T>(IntPtr ptr, T structure)
897 PtrToStructure(ptr, (object)structure);
900 //====================================================================
901 // Creates a new instance of "structuretype" and marshals data from a
902 // native memory block to it.
903 //====================================================================
904 public static Object PtrToStructure(IntPtr ptr, Type structureType)
906 if (ptr == IntPtr.Zero) return null;
908 if (structureType == null)
909 throw new ArgumentNullException(nameof(structureType));
911 if (structureType.IsGenericType)
912 throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(structureType));
914 RuntimeType rt = structureType.UnderlyingSystemType as RuntimeType;
917 throw new ArgumentException(SR.Arg_MustBeType, nameof(structureType));
919 Object structure = rt.CreateInstanceDefaultCtor(false /*publicOnly*/, false /*skipCheckThis*/, false /*fillCache*/, true /*wrapExceptions*/);
920 PtrToStructureHelper(ptr, structure, true);
924 public static T PtrToStructure<T>(IntPtr ptr)
926 return (T)PtrToStructure(ptr, typeof(T));
929 //====================================================================
930 // Helper function to copy a pointer into a preallocated structure.
931 //====================================================================
932 [MethodImplAttribute(MethodImplOptions.InternalCall)]
933 private static extern void PtrToStructureHelper(IntPtr ptr, Object structure, bool allowValueClasses);
936 //====================================================================
937 // Freeds all substructures pointed to by the native memory block.
938 // "structureclass" is used to provide layout information.
939 //====================================================================
940 [MethodImplAttribute(MethodImplOptions.InternalCall)]
941 public static extern void DestroyStructure(IntPtr ptr, Type structuretype);
943 public static void DestroyStructure<T>(IntPtr ptr)
945 DestroyStructure(ptr, typeof(T));
948 #if FEATURE_COMINTEROP
949 //====================================================================
950 // Returns the HInstance for this module. Returns -1 if the module
951 // doesn't have an HInstance. In Memory (Dynamic) Modules won't have
953 //====================================================================
954 public static IntPtr GetHINSTANCE(Module m)
957 throw new ArgumentNullException(nameof(m));
959 RuntimeModule rtModule = m as RuntimeModule;
960 if (rtModule == null)
962 ModuleBuilder mb = m as ModuleBuilder;
964 rtModule = mb.InternalModule;
967 if (rtModule == null)
968 throw new ArgumentNullException(nameof(m), SR.Argument_MustBeRuntimeModule);
970 return GetHINSTANCE(rtModule.GetNativeHandle());
973 [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
974 private static extern IntPtr GetHINSTANCE(RuntimeModule m);
976 #endif // FEATURE_COMINTEROP
977 //====================================================================
978 // Throws a CLR exception based on the HRESULT.
979 //====================================================================
980 public static void ThrowExceptionForHR(int errorCode)
983 ThrowExceptionForHRInternal(errorCode, IntPtr.Zero);
985 public static void ThrowExceptionForHR(int errorCode, IntPtr errorInfo)
988 ThrowExceptionForHRInternal(errorCode, errorInfo);
991 [MethodImplAttribute(MethodImplOptions.InternalCall)]
992 internal static extern void ThrowExceptionForHRInternal(int errorCode, IntPtr errorInfo);
995 //====================================================================
996 // Converts the HRESULT to a CLR exception.
997 //====================================================================
998 public static Exception GetExceptionForHR(int errorCode)
1001 return GetExceptionForHRInternal(errorCode, IntPtr.Zero);
1005 public static Exception GetExceptionForHR(int errorCode, IntPtr errorInfo)
1008 return GetExceptionForHRInternal(errorCode, errorInfo);
1013 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1014 internal static extern Exception GetExceptionForHRInternal(int errorCode, IntPtr errorInfo);
1017 //====================================================================
1018 // Memory allocation and deallocation.
1019 //====================================================================
1020 public static IntPtr AllocHGlobal(IntPtr cb)
1022 // For backwards compatibility on 32 bit platforms, ensure we pass values between
1023 // Int32.MaxValue and UInt32.MaxValue to Windows. If the binary has had the
1024 // LARGEADDRESSAWARE bit set in the PE header, it may get 3 or 4 GB of user mode
1025 // address space. It is remotely that those allocations could have succeeded,
1026 // though I couldn't reproduce that. In either case, that means we should continue
1027 // throwing an OOM instead of an ArgumentOutOfRangeException for "negative" amounts of memory.
1030 numBytes = new UIntPtr(unchecked((ulong)cb.ToInt64()));
1032 numBytes = new UIntPtr(unchecked((uint)cb.ToInt32()));
1035 IntPtr pNewMem = Win32Native.LocalAlloc_NoSafeHandle(LMEM_FIXED, unchecked(numBytes));
1037 if (pNewMem == IntPtr.Zero)
1039 throw new OutOfMemoryException();
1044 public static IntPtr AllocHGlobal(int cb)
1046 return AllocHGlobal((IntPtr)cb);
1049 public static void FreeHGlobal(IntPtr hglobal)
1051 if (IsNotWin32Atom(hglobal))
1053 if (IntPtr.Zero != Win32Native.LocalFree(hglobal))
1055 ThrowExceptionForHR(GetHRForLastWin32Error());
1060 public static IntPtr ReAllocHGlobal(IntPtr pv, IntPtr cb)
1062 IntPtr pNewMem = Win32Native.LocalReAlloc(pv, cb, LMEM_MOVEABLE);
1063 if (pNewMem == IntPtr.Zero)
1065 throw new OutOfMemoryException();
1071 //====================================================================
1072 // String convertions.
1073 //====================================================================
1074 public static unsafe IntPtr StringToHGlobalAnsi(String s)
1082 int nb = (s.Length + 1) * SystemMaxDBCSCharSize;
1084 // Overflow checking
1086 throw new ArgumentOutOfRangeException(nameof(s));
1088 UIntPtr len = new UIntPtr((uint)nb);
1089 IntPtr hglobal = Win32Native.LocalAlloc_NoSafeHandle(LMEM_FIXED, len);
1091 if (hglobal == IntPtr.Zero)
1093 throw new OutOfMemoryException();
1097 s.ConvertToAnsi((byte*)hglobal, nb, false, false);
1103 public static unsafe IntPtr StringToHGlobalUni(String s)
1111 int nb = (s.Length + 1) * 2;
1113 // Overflow checking
1115 throw new ArgumentOutOfRangeException(nameof(s));
1117 UIntPtr len = new UIntPtr((uint)nb);
1118 IntPtr hglobal = Win32Native.LocalAlloc_NoSafeHandle(LMEM_FIXED, len);
1120 if (hglobal == IntPtr.Zero)
1122 throw new OutOfMemoryException();
1126 fixed (char* firstChar = s)
1128 String.wstrcpy((char*)hglobal, firstChar, s.Length + 1);
1135 public static IntPtr StringToHGlobalAuto(String s)
1137 // Ansi platforms are no longer supported
1138 return StringToHGlobalUni(s);
1141 #if FEATURE_COMINTEROP
1143 //====================================================================
1144 // Converts the CLR exception to an HRESULT. This function also sets
1145 // up an IErrorInfo for the exception.
1146 //====================================================================
1147 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1148 public static extern int GetHRForException(Exception e);
1150 //====================================================================
1151 // Converts the CLR exception to an HRESULT. This function also sets
1152 // up an IErrorInfo for the exception.
1153 // This function is only used in WinRT and converts ObjectDisposedException
1155 //====================================================================
1156 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1157 internal static extern int GetHRForException_WinRT(Exception e);
1159 internal static readonly Guid ManagedNameGuid = new Guid("{0F21F359-AB84-41E8-9A78-36D110E6D2F9}");
1161 //====================================================================
1162 // Given a managed object that wraps an ITypeInfo, return its name
1163 //====================================================================
1164 public static String GetTypeInfoName(ITypeInfo typeInfo)
1166 if (typeInfo == null)
1167 throw new ArgumentNullException(nameof(typeInfo));
1169 String strTypeLibName = null;
1170 String strDocString = null;
1171 int dwHelpContext = 0;
1172 String strHelpFile = null;
1174 typeInfo.GetDocumentation(-1, out strTypeLibName, out strDocString, out dwHelpContext, out strHelpFile);
1176 return strTypeLibName;
1179 // This method is identical to Type.GetTypeFromCLSID. Since it's interop specific, we expose it
1180 // on Marshal for more consistent API surface.
1181 public static Type GetTypeFromCLSID(Guid clsid)
1183 return RuntimeType.GetTypeFromCLSIDImpl(clsid, null, false);
1186 //====================================================================
1187 // return the IUnknown* for an Object if the current context
1188 // is the one where the RCW was first seen. Will return null
1190 //====================================================================
1191 public static IntPtr /* IUnknown* */ GetIUnknownForObject(Object o)
1193 return GetIUnknownForObjectNative(o, false);
1196 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1197 private static extern IntPtr /* IUnknown* */ GetIUnknownForObjectNative(Object o, bool onlyInContext);
1199 //====================================================================
1200 // return the raw IUnknown* for a COM Object not related to current
1202 // Does not call AddRef
1203 //====================================================================
1204 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1205 internal static extern IntPtr /* IUnknown* */ GetRawIUnknownForComObjectNoAddRef(Object o);
1206 #endif // FEATURE_COMINTEROP
1208 //====================================================================
1209 // return the IDispatch* for an Object
1210 //====================================================================
1211 public static IntPtr /* IDispatch */ GetIDispatchForObject(Object o)
1213 throw new PlatformNotSupportedException();
1216 #if FEATURE_COMINTEROP
1218 //====================================================================
1219 // return the IUnknown* representing the interface for the Object
1220 // Object o should support Type T
1221 //====================================================================
1222 public static IntPtr /* IUnknown* */ GetComInterfaceForObject(Object o, Type T)
1224 return GetComInterfaceForObjectNative(o, T, false, true);
1227 public static IntPtr GetComInterfaceForObject<T, TInterface>(T o)
1229 return GetComInterfaceForObject(o, typeof(TInterface));
1232 //====================================================================
1233 // return the IUnknown* representing the interface for the Object
1234 // Object o should support Type T, it refer the value of mode to
1235 // invoke customized QueryInterface or not
1236 //====================================================================
1237 public static IntPtr /* IUnknown* */ GetComInterfaceForObject(Object o, Type T, CustomQueryInterfaceMode mode)
1239 bool bEnableCustomizedQueryInterface = ((mode == CustomQueryInterfaceMode.Allow) ? true : false);
1240 return GetComInterfaceForObjectNative(o, T, false, bEnableCustomizedQueryInterface);
1243 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1244 private static extern IntPtr /* IUnknown* */ GetComInterfaceForObjectNative(Object o, Type t, bool onlyInContext, bool fEnalbeCustomizedQueryInterface);
1246 //====================================================================
1247 // return an Object for IUnknown
1248 //====================================================================
1249 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1250 public static extern Object GetObjectForIUnknown(IntPtr /* IUnknown* */ pUnk);
1252 //====================================================================
1253 // Return a unique Object given an IUnknown. This ensures that you
1254 // receive a fresh object (we will not look in the cache to match up this
1255 // IUnknown to an already existing object). This is useful in cases
1256 // where you want to be able to call ReleaseComObject on a RCW
1257 // and not worry about other active uses of said RCW.
1258 //====================================================================
1259 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1260 public static extern Object GetUniqueObjectForIUnknown(IntPtr unknown);
1262 //====================================================================
1263 // return an Object for IUnknown, using the Type T,
1265 // Type T should be either a COM imported Type or a sub-type of COM
1267 //====================================================================
1268 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1269 public static extern Object GetTypedObjectForIUnknown(IntPtr /* IUnknown* */ pUnk, Type t);
1271 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1272 public static extern IntPtr CreateAggregatedObject(IntPtr pOuter, Object o);
1274 public static IntPtr CreateAggregatedObject<T>(IntPtr pOuter, T o)
1276 return CreateAggregatedObject(pOuter, (object)o);
1279 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1280 public static extern void CleanupUnusedObjectsInCurrentContext();
1282 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1283 public static extern bool AreComObjectsAvailableForCleanup();
1285 //====================================================================
1286 // check if the object is classic COM component
1287 //====================================================================
1288 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1289 public static extern bool IsComObject(Object o);
1291 #endif // FEATURE_COMINTEROP
1293 public static IntPtr AllocCoTaskMem(int cb)
1295 IntPtr pNewMem = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)cb));
1296 if (pNewMem == IntPtr.Zero)
1298 throw new OutOfMemoryException();
1303 public static unsafe IntPtr StringToCoTaskMemUni(String s)
1311 int nb = (s.Length + 1) * 2;
1313 // Overflow checking
1315 throw new ArgumentOutOfRangeException(nameof(s));
1317 IntPtr hglobal = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb));
1319 if (hglobal == IntPtr.Zero)
1321 throw new OutOfMemoryException();
1325 fixed (char* firstChar = s)
1327 String.wstrcpy((char*)hglobal, firstChar, s.Length + 1);
1334 public static unsafe IntPtr StringToCoTaskMemUTF8(String s)
1342 int nb = Encoding.UTF8.GetMaxByteCount(s.Length);
1344 IntPtr pMem = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb + 1));
1346 if (pMem == IntPtr.Zero)
1348 throw new OutOfMemoryException();
1352 fixed (char* firstChar = s)
1354 byte* pbMem = (byte*)pMem;
1355 int nbWritten = Encoding.UTF8.GetBytes(firstChar, s.Length, pbMem, nb);
1356 pbMem[nbWritten] = 0;
1363 public static IntPtr StringToCoTaskMemAuto(String s)
1365 // Ansi platforms are no longer supported
1366 return StringToCoTaskMemUni(s);
1369 public static unsafe IntPtr StringToCoTaskMemAnsi(String s)
1377 int nb = (s.Length + 1) * SystemMaxDBCSCharSize;
1379 // Overflow checking
1381 throw new ArgumentOutOfRangeException(nameof(s));
1383 IntPtr hglobal = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb));
1385 if (hglobal == IntPtr.Zero)
1387 throw new OutOfMemoryException();
1391 s.ConvertToAnsi((byte*)hglobal, nb, false, false);
1397 public static void FreeCoTaskMem(IntPtr ptr)
1399 if (IsNotWin32Atom(ptr))
1401 Win32Native.CoTaskMemFree(ptr);
1405 public static IntPtr ReAllocCoTaskMem(IntPtr pv, int cb)
1407 IntPtr pNewMem = Win32Native.CoTaskMemRealloc(pv, new UIntPtr((uint)cb));
1408 if (pNewMem == IntPtr.Zero && cb != 0)
1410 throw new OutOfMemoryException();
1415 //====================================================================
1416 // BSTR allocation and dealocation.
1417 //====================================================================
1418 public static void FreeBSTR(IntPtr ptr)
1420 if (IsNotWin32Atom(ptr))
1422 Win32Native.SysFreeString(ptr);
1426 public static IntPtr StringToBSTR(String s)
1431 // Overflow checking
1432 if (s.Length + 1 < s.Length)
1433 throw new ArgumentOutOfRangeException(nameof(s));
1435 IntPtr bstr = Win32Native.SysAllocStringLen(s, s.Length);
1436 if (bstr == IntPtr.Zero)
1437 throw new OutOfMemoryException();
1442 public static String PtrToStringBSTR(IntPtr ptr)
1444 return PtrToStringUni(ptr, (int)Win32Native.SysStringLen(ptr));
1447 #if FEATURE_COMINTEROP
1448 //====================================================================
1449 // release the COM component and if the reference hits 0 zombie this object
1450 // further usage of this Object might throw an exception
1451 //====================================================================
1452 public static int ReleaseComObject(Object o)
1454 __ComObject co = null;
1456 // Make sure the obj is an __ComObject.
1459 co = (__ComObject)o;
1461 catch (InvalidCastException)
1463 throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o));
1466 return co.ReleaseSelf();
1469 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1470 internal static extern int InternalReleaseComObject(Object o);
1473 //====================================================================
1474 // release the COM component and zombie this object
1475 // further usage of this Object might throw an exception
1476 //====================================================================
1477 public static Int32 FinalReleaseComObject(Object o)
1480 throw new ArgumentNullException(nameof(o));
1482 __ComObject co = null;
1484 // Make sure the obj is an __ComObject.
1487 co = (__ComObject)o;
1489 catch (InvalidCastException)
1491 throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o));
1494 co.FinalReleaseSelf();
1499 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1500 internal static extern void InternalFinalReleaseComObject(Object o);
1501 #endif // FEATURE_COMINTEROP
1503 //====================================================================
1504 // This method retrieves data from the COM object.
1505 //====================================================================
1506 public static Object GetComObjectData(Object obj, Object key)
1508 throw new PlatformNotSupportedException(SR.Arg_PlatformNotSupported);
1511 //====================================================================
1512 // This method sets data on the COM object. The data can only be set
1513 // once for a given key and cannot be removed. This function returns
1514 // true if the data has been added, false if the data could not be
1515 // added because there already was data for the specified key.
1516 //====================================================================
1517 public static bool SetComObjectData(Object obj, Object key, Object data)
1519 throw new PlatformNotSupportedException(SR.Arg_PlatformNotSupported);
1522 #if FEATURE_COMINTEROP
1523 //====================================================================
1524 // This method takes the given COM object and wraps it in an object
1525 // of the specified type. The type must be derived from __ComObject.
1526 //====================================================================
1527 public static Object CreateWrapperOfType(Object o, Type t)
1529 // Validate the arguments.
1531 throw new ArgumentNullException(nameof(t));
1533 throw new ArgumentException(SR.Argument_TypeNotComObject, nameof(t));
1534 if (t.IsGenericType)
1535 throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t));
1537 if (t.IsWindowsRuntimeObject)
1538 throw new ArgumentException(SR.Argument_TypeIsWinRTType, nameof(t));
1540 // Check for the null case.
1544 // Make sure the object is a COM object.
1545 if (!o.GetType().IsCOMObject)
1546 throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o));
1547 if (o.GetType().IsWindowsRuntimeObject)
1548 throw new ArgumentException(SR.Argument_ObjIsWinRTObject, nameof(o));
1550 // Check to see if the type of the object is the requested type.
1551 if (o.GetType() == t)
1554 // Check to see if we already have a cached wrapper for this type.
1555 Object Wrapper = GetComObjectData(o, t);
1556 if (Wrapper == null)
1558 // Create the wrapper for the specified type.
1559 Wrapper = InternalCreateWrapperOfType(o, t);
1561 // Attempt to cache the wrapper on the object.
1562 if (!SetComObjectData(o, t, Wrapper))
1564 // Another thead already cached the wrapper so use that one instead.
1565 Wrapper = GetComObjectData(o, t);
1572 public static TWrapper CreateWrapperOfType<T, TWrapper>(T o)
1574 return (TWrapper)CreateWrapperOfType(o, typeof(TWrapper));
1577 //====================================================================
1578 // Helper method called from CreateWrapperOfType.
1579 //====================================================================
1580 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1581 private static extern Object InternalCreateWrapperOfType(Object o, Type t);
1583 //====================================================================
1585 //====================================================================
1586 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1587 public static extern int /* HRESULT */ QueryInterface(IntPtr /* IUnknown */ pUnk, ref Guid iid, out IntPtr ppv);
1589 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1590 public static extern int /* ULONG */ AddRef(IntPtr /* IUnknown */ pUnk);
1591 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1592 public static extern int /* ULONG */ Release(IntPtr /* IUnknown */ pUnk);
1594 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1595 public static extern void GetNativeVariantForObject(Object obj, /* VARIANT * */ IntPtr pDstNativeVariant);
1597 public static void GetNativeVariantForObject<T>(T obj, IntPtr pDstNativeVariant)
1599 GetNativeVariantForObject((object)obj, pDstNativeVariant);
1602 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1603 public static extern Object GetObjectForNativeVariant(/* VARIANT * */ IntPtr pSrcNativeVariant);
1605 public static T GetObjectForNativeVariant<T>(IntPtr pSrcNativeVariant)
1607 return (T)GetObjectForNativeVariant(pSrcNativeVariant);
1610 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1611 public static extern Object[] GetObjectsForNativeVariants(/* VARIANT * */ IntPtr aSrcNativeVariant, int cVars);
1613 public static T[] GetObjectsForNativeVariants<T>(IntPtr aSrcNativeVariant, int cVars)
1615 object[] objects = GetObjectsForNativeVariants(aSrcNativeVariant, cVars);
1618 if (objects != null)
1620 result = new T[objects.Length];
1621 Array.Copy(objects, result, objects.Length);
1628 /// <para>Returns the first valid COM slot that GetMethodInfoForSlot will work on
1629 /// This will be 3 for IUnknown based interfaces and 7 for IDispatch based interfaces. </para>
1631 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1632 public static extern int GetStartComSlot(Type t);
1634 #endif // FEATURE_COMINTEROP
1636 //====================================================================
1637 // This method generates a GUID for the specified type. If the type
1638 // has a GUID in the metadata then it is returned otherwise a stable
1639 // guid GUID is generated based on the fully qualified name of the
1641 //====================================================================
1642 public static Guid GenerateGuidForType(Type type)
1647 //====================================================================
1648 // This method generates a PROGID for the specified type. If the type
1649 // has a PROGID in the metadata then it is returned otherwise a stable
1650 // PROGID is generated based on the fully qualified name of the
1652 //====================================================================
1653 public static String GenerateProgIdForType(Type type)
1656 throw new ArgumentNullException(nameof(type));
1658 throw new ArgumentException(SR.Argument_TypeMustNotBeComImport, nameof(type));
1659 if (type.IsGenericType)
1660 throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(type));
1662 IList<CustomAttributeData> cas = CustomAttributeData.GetCustomAttributes(type);
1663 for (int i = 0; i < cas.Count; i++)
1665 if (cas[i].Constructor.DeclaringType == typeof(ProgIdAttribute))
1667 // Retrieve the PROGID string from the ProgIdAttribute.
1668 IList<CustomAttributeTypedArgument> caConstructorArgs = cas[i].ConstructorArguments;
1669 Debug.Assert(caConstructorArgs.Count == 1, "caConstructorArgs.Count == 1");
1671 CustomAttributeTypedArgument progIdConstructorArg = caConstructorArgs[0];
1672 Debug.Assert(progIdConstructorArg.ArgumentType == typeof(String), "progIdConstructorArg.ArgumentType == typeof(String)");
1674 String strProgId = (String)progIdConstructorArg.Value;
1676 if (strProgId == null)
1677 strProgId = String.Empty;
1683 // If there is no prog ID attribute then use the full name of the type as the prog id.
1684 return type.FullName;
1687 #if FEATURE_COMINTEROP
1688 //====================================================================
1689 // This method binds to the specified moniker.
1690 //====================================================================
1691 public static Object BindToMoniker(String monikerName)
1694 IBindCtx bindctx = null;
1695 CreateBindCtx(0, out bindctx);
1698 IMoniker pmoniker = null;
1699 MkParseDisplayName(bindctx, monikerName, out cbEaten, out pmoniker);
1701 BindMoniker(pmoniker, 0, ref IID_IUnknown, out obj);
1705 [DllImport(Interop.Libraries.Ole32, PreserveSig = false)]
1706 private static extern void CreateBindCtx(UInt32 reserved, out IBindCtx ppbc);
1708 [DllImport(Interop.Libraries.Ole32, PreserveSig = false)]
1709 private static extern void MkParseDisplayName(IBindCtx pbc, [MarshalAs(UnmanagedType.LPWStr)] String szUserName, out UInt32 pchEaten, out IMoniker ppmk);
1711 [DllImport(Interop.Libraries.Ole32, PreserveSig = false)]
1712 private static extern void BindMoniker(IMoniker pmk, UInt32 grfOpt, ref Guid iidResult, [MarshalAs(UnmanagedType.Interface)] out Object ppvResult);
1714 //========================================================================
1715 // Private method called from EE upon use of license/ICF2 marshaling.
1716 //========================================================================
1717 private static IntPtr LoadLicenseManager()
1719 Type t = Type.GetType("System.ComponentModel.LicenseManager, System", throwOnError: true);
1720 return t.TypeHandle.Value;
1723 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1724 public static extern void ChangeWrapperHandleStrength(Object otp, bool fIsWeak);
1726 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1727 internal static extern void InitializeWrapperForWinRT(object o, ref IntPtr pUnk);
1729 #if FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION
1730 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1731 internal static extern void InitializeManagedWinRTFactoryObject(object o, RuntimeType runtimeClassType);
1734 //========================================================================
1735 // Create activation factory and wraps it with a unique RCW
1736 //========================================================================
1737 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1738 internal static extern object GetNativeActivationFactory(Type type);
1740 #endif // FEATURE_COMINTEROP
1742 public static Delegate GetDelegateForFunctionPointer(IntPtr ptr, Type t)
1744 // Validate the parameters
1745 if (ptr == IntPtr.Zero)
1746 throw new ArgumentNullException(nameof(ptr));
1749 throw new ArgumentNullException(nameof(t));
1751 if ((t as RuntimeType) == null)
1752 throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(t));
1754 if (t.IsGenericType)
1755 throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t));
1757 Type c = t.BaseType;
1758 if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate)))
1759 throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(t));
1761 return GetDelegateForFunctionPointerInternal(ptr, t);
1764 public static TDelegate GetDelegateForFunctionPointer<TDelegate>(IntPtr ptr)
1766 return (TDelegate)(object)GetDelegateForFunctionPointer(ptr, typeof(TDelegate));
1769 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1770 internal static extern Delegate GetDelegateForFunctionPointerInternal(IntPtr ptr, Type t);
1772 public static IntPtr GetFunctionPointerForDelegate(Delegate d)
1775 throw new ArgumentNullException(nameof(d));
1777 return GetFunctionPointerForDelegateInternal(d);
1780 public static IntPtr GetFunctionPointerForDelegate<TDelegate>(TDelegate d)
1782 return GetFunctionPointerForDelegate((Delegate)(object)d);
1785 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1786 internal static extern IntPtr GetFunctionPointerForDelegateInternal(Delegate d);
1788 public static IntPtr SecureStringToBSTR(SecureString s)
1792 throw new ArgumentNullException(nameof(s));
1795 return s.MarshalToBSTR();
1798 public static IntPtr SecureStringToCoTaskMemAnsi(SecureString s)
1802 throw new ArgumentNullException(nameof(s));
1805 return s.MarshalToString(globalAlloc: false, unicode: false);
1808 public static IntPtr SecureStringToCoTaskMemUnicode(SecureString s)
1812 throw new ArgumentNullException(nameof(s));
1815 return s.MarshalToString(globalAlloc: false, unicode: true);
1818 public static void ZeroFreeBSTR(IntPtr s)
1820 RuntimeImports.RhZeroMemory(s, (UIntPtr)(Win32Native.SysStringLen(s) * 2));
1824 public static void ZeroFreeCoTaskMemAnsi(IntPtr s)
1826 RuntimeImports.RhZeroMemory(s, (UIntPtr)(Win32Native.lstrlenA(s)));
1830 public static void ZeroFreeCoTaskMemUnicode(IntPtr s)
1832 RuntimeImports.RhZeroMemory(s, (UIntPtr)(Win32Native.lstrlenW(s) * 2));
1836 public static unsafe void ZeroFreeCoTaskMemUTF8(IntPtr s)
1838 RuntimeImports.RhZeroMemory(s, (UIntPtr)System.StubHelpers.StubHelpers.strlen((sbyte*)s));
1842 public static IntPtr SecureStringToGlobalAllocAnsi(SecureString s)
1846 throw new ArgumentNullException(nameof(s));
1849 return s.MarshalToString(globalAlloc: true, unicode: false);
1852 public static IntPtr SecureStringToGlobalAllocUnicode(SecureString s)
1856 throw new ArgumentNullException(nameof(s));
1859 return s.MarshalToString(globalAlloc: true, unicode: true); ;
1862 public static void ZeroFreeGlobalAllocAnsi(IntPtr s)
1864 RuntimeImports.RhZeroMemory(s, (UIntPtr)(Win32Native.lstrlenA(s)));
1868 public static void ZeroFreeGlobalAllocUnicode(IntPtr s)
1870 RuntimeImports.RhZeroMemory(s, (UIntPtr)(Win32Native.lstrlenW(s) * 2));