1 // System.Runtime.InteropServices.Marshal.cs
3 // Sean MacIsaac (macisaac@ximian.com)
4 // Paolo Molaro (lupus@ximian.com)
5 // Dietmar Maurer (dietmar@ximian.com)
6 // Jonathan Chambers (joncham@gmail.com)
8 // (C) 2001-2002 Ximian, Inc.
11 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 using System.Collections;
34 using System.Collections.Generic;
35 using System.Runtime.CompilerServices;
37 using System.Security;
38 using System.Reflection;
39 using System.Threading;
40 using System.Runtime.InteropServices.ComTypes;
43 using System.Runtime.ConstrainedExecution;
48 namespace System.Runtime.InteropServices
50 public static class Marshal
53 public static readonly int SystemMaxDBCSCharSize = 2; // don't know what this is
54 public static readonly int SystemDefaultCharSize = Environment.IsRunningOnWindows ? 2 : 1;
57 [MethodImplAttribute (MethodImplOptions.InternalCall)]
58 private extern static int AddRefInternal (IntPtr pUnk);
61 public static int AddRef (IntPtr pUnk)
64 if (pUnk == IntPtr.Zero)
65 throw new ArgumentException ("Value cannot be null.", "pUnk");
66 return AddRefInternal (pUnk);
68 throw new NotImplementedException ();
73 public static bool AreComObjectsAvailableForCleanup ()
78 [MethodImplAttribute(MethodImplOptions.InternalCall)]
79 public extern static IntPtr AllocCoTaskMem (int cb);
81 [MethodImplAttribute(MethodImplOptions.InternalCall)]
82 internal extern static IntPtr AllocCoTaskMemSize (UIntPtr sizet);
84 [MethodImplAttribute(MethodImplOptions.InternalCall)]
85 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
86 public extern static IntPtr AllocHGlobal (IntPtr cb);
88 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
89 public static IntPtr AllocHGlobal (int cb)
91 return AllocHGlobal ((IntPtr)cb);
95 public static object BindToMoniker (string monikerName)
97 throw new NotImplementedException ();
101 public static void ChangeWrapperHandleStrength (object otp, bool fIsWeak)
103 throw new NotImplementedException ();
106 [MethodImplAttribute(MethodImplOptions.InternalCall)]
107 internal extern static void copy_to_unmanaged (Array source, int startIndex,
108 IntPtr destination, int length);
110 [MethodImplAttribute(MethodImplOptions.InternalCall)]
111 internal extern static void copy_from_unmanaged (IntPtr source, int startIndex,
112 Array destination, int length);
114 public static void Copy (byte[] source, int startIndex, IntPtr destination, int length)
116 copy_to_unmanaged (source, startIndex, destination, length);
119 public static void Copy (char[] source, int startIndex, IntPtr destination, int length)
121 copy_to_unmanaged (source, startIndex, destination, length);
124 public static void Copy (short[] source, int startIndex, IntPtr destination, int length)
126 copy_to_unmanaged (source, startIndex, destination, length);
129 public static void Copy (int[] source, int startIndex, IntPtr destination, int length)
131 copy_to_unmanaged (source, startIndex, destination, length);
134 public static void Copy (long[] source, int startIndex, IntPtr destination, int length)
136 copy_to_unmanaged (source, startIndex, destination, length);
139 public static void Copy (float[] source, int startIndex, IntPtr destination, int length)
141 copy_to_unmanaged (source, startIndex, destination, length);
144 public static void Copy (double[] source, int startIndex, IntPtr destination, int length)
146 copy_to_unmanaged (source, startIndex, destination, length);
149 public static void Copy (IntPtr[] source, int startIndex, IntPtr destination, int length)
151 copy_to_unmanaged (source, startIndex, destination, length);
154 public static void Copy (IntPtr source, byte[] destination, int startIndex, int length)
156 copy_from_unmanaged (source, startIndex, destination, length);
159 public static void Copy (IntPtr source, char[] destination, int startIndex, int length)
161 copy_from_unmanaged (source, startIndex, destination, length);
164 public static void Copy (IntPtr source, short[] destination, int startIndex, int length)
166 copy_from_unmanaged (source, startIndex, destination, length);
169 public static void Copy (IntPtr source, int[] destination, int startIndex, int length)
171 copy_from_unmanaged (source, startIndex, destination, length);
174 public static void Copy (IntPtr source, long[] destination, int startIndex, int length)
176 copy_from_unmanaged (source, startIndex, destination, length);
179 public static void Copy (IntPtr source, float[] destination, int startIndex, int length)
181 copy_from_unmanaged (source, startIndex, destination, length);
184 public static void Copy (IntPtr source, double[] destination, int startIndex, int length)
186 copy_from_unmanaged (source, startIndex, destination, length);
189 public static void Copy (IntPtr source, IntPtr[] destination, int startIndex, int length)
191 copy_from_unmanaged (source, startIndex, destination, length);
194 public static IntPtr CreateAggregatedObject (IntPtr pOuter,
197 throw new NotImplementedException ();
200 public static IntPtr CreateAggregatedObject<T> (IntPtr pOuter, T o) {
201 return CreateAggregatedObject (pOuter, (object)o);
204 public static object CreateWrapperOfType (object o, Type t)
207 throw new PlatformNotSupportedException ();
209 __ComObject co = o as __ComObject;
211 throw new ArgumentException ("o must derive from __ComObject", "o");
213 throw new ArgumentNullException ("t");
215 Type[] itfs = o.GetType ().GetInterfaces ();
216 foreach (Type itf in itfs) {
217 if (itf.IsImport && co.GetInterface (itf) == IntPtr.Zero)
218 throw new InvalidCastException ();
221 return ComInteropProxy.GetProxy (co.IUnknown, t).GetTransparentProxy ();
225 public static TWrapper CreateWrapperOfType<T, TWrapper> (T o) {
226 return (TWrapper)CreateWrapperOfType ((object)o, typeof (TWrapper));
229 [MethodImplAttribute(MethodImplOptions.InternalCall)]
231 public extern static void DestroyStructure (IntPtr ptr, Type structuretype);
233 public static void DestroyStructure<T> (IntPtr ptr) {
234 DestroyStructure (ptr, typeof (T));
237 [MethodImplAttribute(MethodImplOptions.InternalCall)]
238 public extern static void FreeBSTR (IntPtr ptr);
240 [MethodImplAttribute(MethodImplOptions.InternalCall)]
241 public extern static void FreeCoTaskMem (IntPtr ptr);
243 [MethodImplAttribute(MethodImplOptions.InternalCall)]
244 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
245 public extern static void FreeHGlobal (IntPtr hglobal);
247 static void ClearBSTR (IntPtr ptr)
249 int len = ReadInt32 (ptr, -4);
251 for (int i = 0; i < len; i++)
252 WriteByte (ptr, i, 0);
255 public static void ZeroFreeBSTR (IntPtr s)
261 static void ClearAnsi (IntPtr ptr)
263 for (int i = 0; ReadByte (ptr, i) != 0; i++)
264 WriteByte (ptr, i, 0);
267 static void ClearUnicode (IntPtr ptr)
269 for (int i = 0; ReadInt16 (ptr, i) != 0; i += 2)
270 WriteInt16 (ptr, i, 0);
273 public static void ZeroFreeCoTaskMemAnsi (IntPtr s)
279 public static void ZeroFreeCoTaskMemUnicode (IntPtr s)
285 public static void ZeroFreeCoTaskMemUTF8 (IntPtr s)
291 public static void ZeroFreeGlobalAllocAnsi (IntPtr s)
297 public static void ZeroFreeGlobalAllocUnicode (IntPtr s)
303 #if !FULL_AOT_RUNTIME
304 public static Guid GenerateGuidForType (Type type)
309 public static string GenerateProgIdForType (Type type)
311 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (type);
313 foreach (var a in attrs)
315 var dt = a.Constructor.DeclaringType;
316 string name = dt.Name;
317 if (name == "ProgIdAttribute")
319 var args = a.ConstructorArguments;
320 string text = a.ConstructorArguments[0].Value as string;
329 return type.FullName;
333 public static object GetActiveObject (string progID)
335 throw new NotImplementedException ();
339 [MethodImplAttribute (MethodImplOptions.InternalCall)]
340 private extern static IntPtr GetCCW (object o, Type T);
342 private static IntPtr GetComInterfaceForObjectInternal (object o, Type T)
345 return ((__ComObject)o).GetInterface (T);
347 return GetCCW (o, T);
350 #endif // !FULL_AOT_RUNTIME
352 public static IntPtr GetComInterfaceForObject (object o, Type T)
355 throw new PlatformNotSupportedException ();
357 IntPtr pItf = GetComInterfaceForObjectInternal (o, T);
364 public static IntPtr GetComInterfaceForObject (object o, Type T, CustomQueryInterfaceMode mode)
366 throw new NotImplementedException ();
369 public static IntPtr GetComInterfaceForObject<T, TInterface> (T o) {
370 return GetComInterfaceForObject ((object)o, typeof (T));
373 #if !FULL_AOT_RUNTIME
375 public static IntPtr GetComInterfaceForObjectInContext (object o, Type t)
377 throw new NotImplementedException ();
380 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
381 public static object GetComObjectData (object obj, object key)
383 throw new NotSupportedException ("MSDN states user code should never need to call this method.");
387 [MethodImplAttribute(MethodImplOptions.InternalCall)]
388 private extern static int GetComSlotForMethodInfoInternal (MemberInfo m);
391 public static int GetComSlotForMethodInfo (MemberInfo m)
395 throw new ArgumentNullException ("m");
396 if (!(m is MethodInfo))
397 throw new ArgumentException ("The MemberInfo must be an interface method.", "m");
398 if (!m.DeclaringType.IsInterface)
399 throw new ArgumentException ("The MemberInfo must be an interface method.", "m");
400 return GetComSlotForMethodInfoInternal (m);
402 throw new NotImplementedException ();
407 public static int GetEndComSlot (Type t)
409 throw new NotImplementedException ();
414 public static IntPtr GetExceptionPointers()
416 throw new NotImplementedException ();
419 public static IntPtr GetHINSTANCE (Module m)
422 throw new ArgumentNullException ("m");
424 return m.GetHINSTANCE ();
426 #endif // !FULL_AOT_RUNTIME
428 public static int GetExceptionCode ()
430 throw new PlatformNotSupportedException ();
433 public static int GetHRForException (Exception e)
435 if (e == null) return 0;
437 #if FEATURE_COMINTEROP
438 var errorInfo = new ManagedErrorInfo(e);
439 SetErrorInfo (0, errorInfo);
446 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
447 public static int GetHRForLastWin32Error()
450 throw new PlatformNotSupportedException ();
452 throw new NotImplementedException ();
456 #if !FULL_AOT_RUNTIME
457 [MethodImplAttribute (MethodImplOptions.InternalCall)]
458 private extern static IntPtr GetIDispatchForObjectInternal (object o);
460 public static IntPtr GetIDispatchForObject (object o)
462 IntPtr pUnk = GetIDispatchForObjectInternal (o);
463 // Internal method does not AddRef
469 public static IntPtr GetIDispatchForObjectInContext (object o)
471 throw new NotImplementedException ();
475 public static IntPtr GetITypeInfoForType (Type t)
477 throw new NotImplementedException ();
481 public static IntPtr GetIUnknownForObjectInContext (object o)
483 throw new NotImplementedException ();
487 [Obsolete ("This method has been deprecated")]
488 public static IntPtr GetManagedThunkForUnmanagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
490 throw new NotImplementedException ();
494 public static MemberInfo GetMethodInfoForComSlot (Type t, int slot, ref ComMemberType memberType)
496 throw new NotImplementedException ();
499 [MethodImplAttribute (MethodImplOptions.InternalCall)]
500 private extern static IntPtr GetIUnknownForObjectInternal (object o);
502 #endif // !FULL_AOT_RUNTIME
504 public static IntPtr GetIUnknownForObject (object o)
507 throw new PlatformNotSupportedException ();
509 IntPtr pUnk = GetIUnknownForObjectInternal (o);
510 // Internal method does not AddRef
516 public static void GetNativeVariantForObject (object obj, IntPtr pDstNativeVariant)
519 throw new PlatformNotSupportedException ();
521 Variant vt = new Variant();
523 Marshal.StructureToPtr(vt, pDstNativeVariant, false);
527 public static void GetNativeVariantForObject<T> (T obj, IntPtr pDstNativeVariant) {
528 GetNativeVariantForObject ((object)obj, pDstNativeVariant);
531 #if !MOBILE && !FULL_AOT_RUNTIME
532 [MethodImplAttribute (MethodImplOptions.InternalCall)]
533 private static extern object GetObjectForCCW (IntPtr pUnk);
536 public static object GetObjectForIUnknown (IntPtr pUnk)
538 #if MOBILE || FULL_AOT_RUNTIME
539 throw new PlatformNotSupportedException ();
541 object obj = GetObjectForCCW (pUnk);
544 ComInteropProxy proxy = ComInteropProxy.GetProxy (pUnk, typeof (__ComObject));
545 obj = proxy.GetTransparentProxy ();
551 public static object GetObjectForNativeVariant (IntPtr pSrcNativeVariant)
554 throw new PlatformNotSupportedException ();
556 Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
557 return vt.GetValue();
561 public static T GetObjectForNativeVariant<T> (IntPtr pSrcNativeVariant)
564 throw new PlatformNotSupportedException ();
566 Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
567 return (T)vt.GetValue();
571 public static object[] GetObjectsForNativeVariants (IntPtr aSrcNativeVariant, int cVars)
574 throw new PlatformNotSupportedException ();
577 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
578 object[] objects = new object[cVars];
579 for (int i = 0; i < cVars; i++)
580 objects[i] = GetObjectForNativeVariant ((IntPtr)(aSrcNativeVariant.ToInt64 () +
581 i * SizeOf (typeof(Variant))));
586 public static T[] GetObjectsForNativeVariants<T> (IntPtr aSrcNativeVariant, int cVars)
589 throw new PlatformNotSupportedException ();
592 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
593 T[] objects = new T[cVars];
594 for (int i = 0; i < cVars; i++)
595 objects[i] = GetObjectForNativeVariant<T> ((IntPtr)(aSrcNativeVariant.ToInt64 () +
596 i * SizeOf (typeof(Variant))));
602 public static int GetStartComSlot (Type t)
605 throw new PlatformNotSupportedException ();
607 throw new NotImplementedException ();
611 #if !FULL_AOT_RUNTIME
613 [Obsolete ("This method has been deprecated")]
614 public static Thread GetThreadFromFiberCookie (int cookie)
616 throw new NotImplementedException ();
619 public static object GetTypedObjectForIUnknown (IntPtr pUnk, Type t)
621 ComInteropProxy proxy = new ComInteropProxy (pUnk, t);
622 __ComObject co = (__ComObject)proxy.GetTransparentProxy ();
623 foreach (Type itf in t.GetInterfaces ()) {
624 if ((itf.Attributes & TypeAttributes.Import) == TypeAttributes.Import) {
625 if (co.GetInterface (itf) == IntPtr.Zero)
633 public static Type GetTypeForITypeInfo (IntPtr piTypeInfo)
635 throw new NotImplementedException ();
640 public static string GetTypeInfoName (UCOMITypeInfo pTI)
642 throw new NotImplementedException ();
647 public static Guid GetTypeLibGuid (UCOMITypeLib pTLB)
649 throw new NotImplementedException ();
653 public static Guid GetTypeLibGuid (ITypeLib typelib)
655 throw new NotImplementedException ();
659 public static Guid GetTypeLibGuidForAssembly (Assembly asm)
661 throw new NotImplementedException ();
666 public static int GetTypeLibLcid (UCOMITypeLib pTLB)
668 throw new NotImplementedException ();
672 public static int GetTypeLibLcid (ITypeLib typelib)
674 throw new NotImplementedException ();
679 public static string GetTypeLibName (UCOMITypeLib pTLB)
681 throw new NotImplementedException ();
685 public static string GetTypeLibName (ITypeLib typelib)
687 throw new NotImplementedException ();
691 public static void GetTypeLibVersionForAssembly (Assembly inputAssembly, out int majorVersion, out int minorVersion)
693 throw new NotImplementedException ();
697 [Obsolete ("This method has been deprecated")]
698 public static IntPtr GetUnmanagedThunkForManagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
700 throw new NotImplementedException ();
704 public static bool IsTypeVisibleFromCom (Type t)
706 throw new NotImplementedException ();
710 public static int NumParamBytes (MethodInfo m)
712 throw new NotImplementedException ();
714 #endif // !FULL_AOT_RUNTIME
716 public static Type GetTypeFromCLSID (Guid clsid)
718 throw new PlatformNotSupportedException ();
721 public static string GetTypeInfoName (ITypeInfo typeInfo)
723 throw new PlatformNotSupportedException ();
726 public static object GetUniqueObjectForIUnknown (IntPtr unknown)
728 throw new PlatformNotSupportedException ();
732 [MethodImplAttribute (MethodImplOptions.InternalCall)]
733 public extern static bool IsComObject (object o);
735 public static bool IsComObject (object o)
737 throw new PlatformNotSupportedException ();
741 [MethodImplAttribute(MethodImplOptions.InternalCall)]
742 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
743 public static extern int GetLastWin32Error();
745 [MethodImplAttribute(MethodImplOptions.InternalCall)]
746 public extern static IntPtr OffsetOf (Type t, string fieldName);
748 public static IntPtr OffsetOf<T> (string fieldName) {
749 return OffsetOf (typeof (T), fieldName);
752 [MethodImplAttribute(MethodImplOptions.InternalCall)]
753 public extern static void Prelink (MethodInfo m);
755 [MethodImplAttribute(MethodImplOptions.InternalCall)]
756 public extern static void PrelinkAll (Type c);
758 [MethodImplAttribute(MethodImplOptions.InternalCall)]
759 public extern static string PtrToStringAnsi (IntPtr ptr);
761 [MethodImplAttribute(MethodImplOptions.InternalCall)]
762 public extern static string PtrToStringAnsi (IntPtr ptr, int len);
764 public static string PtrToStringUTF8 (IntPtr ptr)
766 return PtrToStringAnsi (ptr);
769 public static string PtrToStringUTF8 (IntPtr ptr, int byteLen)
771 return PtrToStringAnsi (ptr, byteLen);
774 public static string PtrToStringAuto (IntPtr ptr)
776 return SystemDefaultCharSize == 2
777 ? PtrToStringUni (ptr) : PtrToStringAnsi (ptr);
780 public static string PtrToStringAuto (IntPtr ptr, int len)
782 return SystemDefaultCharSize == 2
783 ? PtrToStringUni (ptr, len) : PtrToStringAnsi (ptr, len);
786 [MethodImplAttribute(MethodImplOptions.InternalCall)]
787 public extern static string PtrToStringUni (IntPtr ptr);
789 [MethodImplAttribute(MethodImplOptions.InternalCall)]
790 public extern static string PtrToStringUni (IntPtr ptr, int len);
792 [MethodImplAttribute(MethodImplOptions.InternalCall)]
793 public extern static string PtrToStringBSTR (IntPtr ptr);
795 [MethodImplAttribute(MethodImplOptions.InternalCall)]
797 public extern static void PtrToStructure (IntPtr ptr, object structure);
799 [MethodImplAttribute(MethodImplOptions.InternalCall)]
801 public extern static object PtrToStructure (IntPtr ptr, Type structureType);
803 public static void PtrToStructure<T> (IntPtr ptr, T structure) {
804 PtrToStructure (ptr, (object)structure);
807 public static T PtrToStructure<T> (IntPtr ptr) {
808 return (T) PtrToStructure (ptr, typeof (T));
812 [MethodImplAttribute (MethodImplOptions.InternalCall)]
813 private extern static int QueryInterfaceInternal (IntPtr pUnk, ref Guid iid, out IntPtr ppv);
816 public static int QueryInterface (IntPtr pUnk, ref Guid iid, out IntPtr ppv)
819 if (pUnk == IntPtr.Zero)
820 throw new ArgumentException ("Value cannot be null.", "pUnk");
821 return QueryInterfaceInternal (pUnk, ref iid, out ppv);
823 throw new NotImplementedException ();
827 public static byte ReadByte (IntPtr ptr)
834 public static byte ReadByte (IntPtr ptr, int ofs) {
836 return *((byte*)ptr + ofs);
841 [SuppressUnmanagedCodeSecurity]
842 public static byte ReadByte ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
844 throw new NotImplementedException ();
847 public unsafe static short ReadInt16 (IntPtr ptr)
849 byte *addr = (byte *) ptr;
851 // The mono JIT can't inline this due to the hight number of calls
852 // return ReadInt16 (ptr, 0);
854 if (((uint)addr & 1) == 0)
855 return *(short*)addr;
858 Buffer.Memcpy ((byte*)&s, (byte*)ptr, 2);
862 public unsafe static short ReadInt16 (IntPtr ptr, int ofs)
864 byte *addr = ((byte *) ptr) + ofs;
866 if (((uint) addr & 1) == 0)
867 return *(short*)addr;
870 Buffer.Memcpy ((byte*)&s, addr, 2);
875 [SuppressUnmanagedCodeSecurity]
876 public static short ReadInt16 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
878 throw new NotImplementedException ();
881 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
882 public unsafe static int ReadInt32 (IntPtr ptr)
884 byte *addr = (byte *) ptr;
886 if (((uint)addr & 3) == 0)
890 Buffer.Memcpy ((byte*)&s, addr, 4);
894 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
895 public unsafe static int ReadInt32 (IntPtr ptr, int ofs)
897 byte *addr = ((byte *) ptr) + ofs;
899 if ((((int) addr) & 3) == 0)
903 Buffer.Memcpy ((byte*)&s, addr, 4);
908 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
910 [SuppressUnmanagedCodeSecurity]
911 public static int ReadInt32 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
913 throw new NotImplementedException ();
916 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
917 public unsafe static long ReadInt64 (IntPtr ptr)
919 byte *addr = (byte *) ptr;
921 // The real alignment might be 4 on some platforms, but this is just an optimization,
922 // so it doesn't matter.
923 if (((uint) addr & 7) == 0)
927 Buffer.Memcpy ((byte*)&s, addr, 8);
931 public unsafe static long ReadInt64 (IntPtr ptr, int ofs)
933 byte *addr = ((byte *) ptr) + ofs;
935 if (((uint) addr & 7) == 0)
939 Buffer.Memcpy ((byte*)&s, addr, 8);
943 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
945 [SuppressUnmanagedCodeSecurity]
946 public static long ReadInt64 ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
948 throw new NotImplementedException ();
951 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
952 public static IntPtr ReadIntPtr (IntPtr ptr)
954 if (IntPtr.Size == 4)
955 return (IntPtr)ReadInt32 (ptr);
957 return (IntPtr)ReadInt64 (ptr);
960 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
961 public static IntPtr ReadIntPtr (IntPtr ptr, int ofs)
963 if (IntPtr.Size == 4)
964 return (IntPtr)ReadInt32 (ptr, ofs);
966 return (IntPtr)ReadInt64 (ptr, ofs);
969 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
971 public static IntPtr ReadIntPtr ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
973 throw new NotImplementedException ();
976 [MethodImplAttribute (MethodImplOptions.InternalCall)]
977 public extern static IntPtr ReAllocCoTaskMem (IntPtr pv, int cb);
979 [MethodImplAttribute(MethodImplOptions.InternalCall)]
980 public extern static IntPtr ReAllocHGlobal (IntPtr pv, IntPtr cb);
983 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
984 [MethodImplAttribute (MethodImplOptions.InternalCall)]
985 private extern static int ReleaseInternal (IntPtr pUnk);
988 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
989 public static int Release (IntPtr pUnk)
992 if (pUnk == IntPtr.Zero)
993 throw new ArgumentException ("Value cannot be null.", "pUnk");
995 return ReleaseInternal (pUnk);
997 throw new NotImplementedException ();
1001 #if !FULL_AOT_RUNTIME
1002 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1003 private extern static int ReleaseComObjectInternal (object co);
1006 public static int ReleaseComObject (object o)
1008 #if FULL_AOT_RUNTIME
1009 throw new PlatformNotSupportedException ();
1012 throw new ArgumentException ("Value cannot be null.", "o");
1013 if (!IsComObject (o))
1014 throw new ArgumentException ("Value must be a Com object.", "o");
1015 return ReleaseComObjectInternal (o);
1019 #if !FULL_AOT_RUNTIME
1022 public static void ReleaseThreadCache()
1024 throw new NotImplementedException ();
1027 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
1028 public static bool SetComObjectData (object obj, object key, object data)
1030 throw new NotSupportedException ("MSDN states user code should never need to call this method.");
1035 public static int SizeOf (object structure)
1037 return SizeOf (structure.GetType ());
1040 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1041 public extern static int SizeOf (Type t);
1043 public static int SizeOf<T> () {
1044 return SizeOf (typeof (T));
1047 public static int SizeOf<T> (T structure) {
1048 return SizeOf (structure.GetType ());
1051 internal static uint SizeOfType (Type type)
1053 return (uint) SizeOf (type);
1056 internal static uint AlignedSizeOf<T> () where T : struct
1058 uint size = SizeOfType (typeof (T));
1059 if (size == 1 || size == 2)
1061 if (IntPtr.Size == 8 && size == 4)
1063 return (size + 3) & (~((uint)3));
1066 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1067 public extern static IntPtr StringToBSTR (string s);
1069 public static IntPtr StringToCoTaskMemAnsi (string s)
1071 return StringToAllocatedMemoryUTF8 (s);
1074 public static IntPtr StringToCoTaskMemAuto (string s)
1076 return SystemDefaultCharSize == 2
1077 ? StringToCoTaskMemUni (s) : StringToCoTaskMemAnsi (s);
1080 public static IntPtr StringToCoTaskMemUni (string s)
1082 int length = s.Length + 1;
1083 IntPtr ctm = AllocCoTaskMem (length * 2);
1085 char[] asChars = new char[length];
1086 s.CopyTo (0, asChars, 0, s.Length);
1087 asChars[s.Length] = '\0';
1089 copy_to_unmanaged (asChars, 0, ctm, length);
1093 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1094 public extern static IntPtr StringToHGlobalAnsi (string s);
1096 unsafe public static IntPtr StringToAllocatedMemoryUTF8(String s)
1098 const int MAX_UTF8_CHAR_SIZE = 3;
1102 int nb = (s.Length + 1) * MAX_UTF8_CHAR_SIZE;
1104 // Overflow checking
1106 throw new ArgumentOutOfRangeException("s");
1108 IntPtr pMem = AllocCoTaskMemSize(new UIntPtr((uint)nb +1));
1110 if (pMem == IntPtr.Zero)
1111 throw new OutOfMemoryException();
1113 byte* pbMem = (byte*)pMem;
1114 int nbWritten = s.GetBytesFromEncoding(pbMem, nb, Encoding.UTF8);
1115 pbMem[nbWritten] = 0;
1119 public static IntPtr StringToHGlobalAuto (string s)
1121 return SystemDefaultCharSize == 2
1122 ? StringToHGlobalUni (s) : StringToHGlobalAnsi (s);
1125 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1126 public extern static IntPtr StringToHGlobalUni (string s);
1128 public static IntPtr SecureStringToBSTR (SecureString s)
1131 throw new ArgumentNullException ("s");
1133 byte[] buffer = s.GetBuffer ();
1136 // SecureString doesn't take endian-ness into account.
1137 // Therefore swap bytes here before we send it to c-side if little-endian.
1138 if (BitConverter.IsLittleEndian) {
1139 for (int i = 0; i < buffer.Length; i += 2) {
1141 buffer[i] = buffer[i + 1];
1145 return BufferToBSTR (buffer, len);
1148 public static IntPtr SecureStringToCoTaskMemAnsi (SecureString s)
1151 throw new ArgumentNullException ("s");
1153 IntPtr ctm = AllocCoTaskMem (len + 1);
1154 byte [] copy = new byte [len+1];
1157 byte [] buffer = s.GetBuffer ();
1159 for (; i < len; i++, j += 2){
1160 copy [i] = buffer [j+1];
1165 copy_to_unmanaged (copy, 0, ctm, len+1);
1167 // Ensure that we clear the buffer.
1168 for (int i = len; i > 0; ){
1176 public static IntPtr SecureStringToCoTaskMemUnicode (SecureString s)
1179 throw new ArgumentNullException ("s");
1181 IntPtr ctm = AllocCoTaskMem (len * 2 + 2);
1182 byte [] buffer = null;
1184 buffer = s.GetBuffer ();
1185 for (int i = 0; i < len; i++)
1186 WriteInt16 (ctm, i * 2, (short) ((buffer [(i*2)] << 8) | (buffer [i*2+1])));
1187 WriteInt16 (ctm, buffer.Length, 0);
1190 for (int i = buffer.Length; i > 0; ){
1198 public static IntPtr SecureStringToGlobalAllocAnsi (SecureString s)
1201 throw new ArgumentNullException ("s");
1202 return SecureStringToCoTaskMemAnsi (s);
1205 public static IntPtr SecureStringToGlobalAllocUnicode (SecureString s)
1208 throw new ArgumentNullException ("s");
1209 return SecureStringToCoTaskMemUnicode (s);
1212 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
1214 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1215 public extern static void StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld);
1217 public static void StructureToPtr<T> (T structure, IntPtr ptr, bool fDeleteOld) {
1218 StructureToPtr ((object)structure, ptr, fDeleteOld);
1221 public static void ThrowExceptionForHR (int errorCode) {
1222 Exception ex = GetExceptionForHR (errorCode);
1227 public static void ThrowExceptionForHR (int errorCode, IntPtr errorInfo) {
1228 Exception ex = GetExceptionForHR (errorCode, errorInfo);
1234 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1235 public extern static IntPtr BufferToBSTR (Array ptr, int slen);
1237 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1238 public extern static IntPtr UnsafeAddrOfPinnedArrayElement (Array arr, int index);
1240 public static IntPtr UnsafeAddrOfPinnedArrayElement<T> (T[] arr, int index) {
1241 return UnsafeAddrOfPinnedArrayElement ((Array)arr, index);
1244 public static void WriteByte (IntPtr ptr, byte val)
1251 public static void WriteByte (IntPtr ptr, int ofs, byte val) {
1253 *(byte*)(IntPtr.Add (ptr, ofs)) = val;
1258 [SuppressUnmanagedCodeSecurity]
1259 public static void WriteByte ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, byte val)
1261 throw new NotImplementedException ();
1264 public static unsafe void WriteInt16 (IntPtr ptr, short val)
1266 byte *addr = (byte *) ptr;
1268 if (((uint)addr & 1) == 0)
1269 *(short*)addr = val;
1271 Buffer.Memcpy (addr, (byte*)&val, 2);
1274 public static unsafe void WriteInt16 (IntPtr ptr, int ofs, short val)
1276 byte *addr = ((byte *) ptr) + ofs;
1278 if (((uint)addr & 1) == 0)
1279 *(short*)addr = val;
1281 Buffer.Memcpy (addr, (byte*)&val, 2);
1286 [SuppressUnmanagedCodeSecurity]
1287 public static void WriteInt16 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, short val)
1289 throw new NotImplementedException ();
1292 public static void WriteInt16 (IntPtr ptr, char val)
1294 WriteInt16 (ptr, 0, (short)val);
1297 public static void WriteInt16 (IntPtr ptr, int ofs, char val)
1299 WriteInt16 (ptr, ofs, (short)val);
1303 public static void WriteInt16([In, Out] object ptr, int ofs, char val)
1305 throw new NotImplementedException ();
1308 public static unsafe void WriteInt32 (IntPtr ptr, int val)
1310 byte *addr = (byte *) ptr;
1312 if (((uint)addr & 3) == 0)
1315 Buffer.Memcpy (addr, (byte*)&val, 4);
1319 public unsafe static void WriteInt32 (IntPtr ptr, int ofs, int val)
1321 byte *addr = ((byte *) ptr) + ofs;
1323 if (((uint)addr & 3) == 0)
1326 Buffer.Memcpy (addr, (byte*)&val, 4);
1331 [SuppressUnmanagedCodeSecurity]
1332 public static void WriteInt32([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, int val)
1334 throw new NotImplementedException ();
1337 public static unsafe void WriteInt64 (IntPtr ptr, long val)
1339 byte *addr = (byte *) ptr;
1341 // The real alignment might be 4 on some platforms, but this is just an optimization,
1342 // so it doesn't matter.
1343 if (((uint)addr & 7) == 0)
1346 Buffer.Memcpy (addr, (byte*)&val, 8);
1349 public static unsafe void WriteInt64 (IntPtr ptr, int ofs, long val)
1351 byte *addr = ((byte *) ptr) + ofs;
1353 // The real alignment might be 4 on some platforms, but this is just an optimization,
1354 // so it doesn't matter.
1355 if (((uint)addr & 7) == 0)
1358 Buffer.Memcpy (addr, (byte*)&val, 8);
1362 [SuppressUnmanagedCodeSecurity]
1363 public static void WriteInt64 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, long val)
1365 throw new NotImplementedException ();
1368 public static void WriteIntPtr (IntPtr ptr, IntPtr val)
1370 if (IntPtr.Size == 4)
1371 WriteInt32 (ptr, (int)val);
1373 WriteInt64 (ptr, (long)val);
1376 public static void WriteIntPtr (IntPtr ptr, int ofs, IntPtr val)
1378 if (IntPtr.Size == 4)
1379 WriteInt32 (ptr, ofs, (int)val);
1381 WriteInt64 (ptr, ofs, (long)val);
1385 public static void WriteIntPtr([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, IntPtr val)
1387 throw new NotImplementedException ();
1390 private static Exception ConvertHrToException (int errorCode)
1392 const int MSEE_E_APPDOMAINUNLOADED = unchecked ((int)0x80131014L);
1393 const int COR_E_APPLICATION = unchecked ((int)0x80131600L);
1394 const int E_INVALIDARG = unchecked ((int)0x80070057);
1395 const int COR_E_ARGUMENTOUTOFRANGE = unchecked ((int)0x80131502L);
1396 const int COR_E_ARITHMETIC = unchecked ((int)0x80070216);
1397 const int COR_E_ARRAYTYPEMISMATCH = unchecked ((int)0x80131503L);
1398 const int COR_E_BADIMAGEFORMAT = unchecked ((int)0x8007000BL);
1399 const int ERROR_BAD_FORMAT = unchecked ((int)0x0B);
1400 //const int COR_E_COMEMULATE_ERROR = unchecked ((int)?);
1401 const int COR_E_CONTEXTMARSHAL = unchecked ((int)0x80131504L);
1402 //const int COR_E_CORE = unchecked ((int)?);
1403 const int NTE_FAIL = unchecked ((int)0x80090020L);
1404 const int COR_E_DIRECTORYNOTFOUND = unchecked ((int)0x80070003L);
1405 const int ERROR_PATH_NOT_FOUND = unchecked ((int)0x03);
1406 const int COR_E_DIVIDEBYZERO = unchecked ((int)0x80020012L);
1407 const int COR_E_DUPLICATEWAITOBJECT = unchecked ((int)0x80131529L);
1408 const int COR_E_ENDOFSTREAM = unchecked ((int)0x80070026L);
1409 const int COR_E_TYPELOAD = unchecked ((int)0x80131522L);
1410 const int COR_E_EXCEPTION = unchecked ((int)0x80131500L);
1411 const int COR_E_EXECUTIONENGINE = unchecked ((int)0x80131506L);
1412 const int COR_E_FIELDACCESS = unchecked ((int)0x80131507L);
1413 const int COR_E_FILENOTFOUND = unchecked ((int)0x80070002L);
1414 const int ERROR_FILE_NOT_FOUND = unchecked ((int)0x02);
1415 const int COR_E_FORMAT = unchecked ((int)0x80131537L);
1416 const int COR_E_INDEXOUTOFRANGE = unchecked ((int)0x80131508L);
1417 const int COR_E_INVALIDCAST = unchecked ((int)0x80004002L);
1418 const int COR_E_INVALIDCOMOBJECT = unchecked ((int)0x80131527L);
1419 const int COR_E_INVALIDFILTERCRITERIA = unchecked ((int)0x80131601L);
1420 const int COR_E_INVALIDOLEVARIANTTYPE = unchecked ((int)0x80131531L);
1421 const int COR_E_INVALIDOPERATION = unchecked ((int)0x80131509L);
1422 const int COR_E_IO = unchecked ((int)0x80131620L);
1423 const int COR_E_MEMBERACCESS = unchecked ((int)0x8013151AL);
1424 const int COR_E_METHODACCESS = unchecked ((int)0x80131510L);
1425 const int COR_E_MISSINGFIELD = unchecked ((int)0x80131511L);
1426 const int COR_E_MISSINGMANIFESTRESOURCE = unchecked ((int)0x80131532L);
1427 const int COR_E_MISSINGMEMBER = unchecked ((int)0x80131512L);
1428 const int COR_E_MISSINGMETHOD = unchecked ((int)0x80131513L);
1429 const int COR_E_MULTICASTNOTSUPPORTED = unchecked ((int)0x80131514L);
1430 const int COR_E_NOTFINITENUMBER = unchecked ((int)0x80131528L);
1431 const int E_NOTIMPL = unchecked ((int)0x80004001L);
1432 const int COR_E_NOTSUPPORTED = unchecked ((int)0x80131515L);
1433 const int COR_E_NULLREFERENCE = unchecked ((int)0x80004003L);
1434 const int E_OUTOFMEMORY = unchecked ((int)0x8007000EL);
1435 const int COR_E_OVERFLOW = unchecked ((int)0x80131516L);
1436 const int COR_E_PATHTOOLONG = unchecked ((int)0x800700CEL);
1437 const int ERROR_FILENAME_EXCED_RANGE = unchecked ((int)0xCE);
1438 const int COR_E_RANK = unchecked ((int)0x80131517L);
1439 const int COR_E_REFLECTIONTYPELOAD = unchecked ((int)0x80131602L);
1440 const int COR_E_REMOTING = unchecked ((int)0x8013150BL);
1441 const int COR_E_SAFEARRAYTYPEMISMATCH = unchecked ((int)0x80131533L);
1442 const int COR_E_SECURITY = unchecked ((int)0x8013150AL);
1443 const int COR_E_SERIALIZATION = unchecked ((int)0x8013150CL);
1444 const int COR_E_STACKOVERFLOW = unchecked ((int)0x800703E9L);
1445 const int ERROR_STACK_OVERFLOW = unchecked ((int)0x03E9);
1446 const int COR_E_SYNCHRONIZATIONLOCK = unchecked ((int)0x80131518L);
1447 const int COR_E_SYSTEM = unchecked ((int)0x80131501L);
1448 const int COR_E_TARGET = unchecked ((int)0x80131603L);
1449 const int COR_E_TARGETINVOCATION = unchecked ((int)0x80131604L);
1450 const int COR_E_TARGETPARAMCOUNT = unchecked ((int)0x8002000EL);
1451 //const int COR_E_THREADABORTED = unchecked ((int)0x80131530L);
1452 const int COR_E_THREADINTERRUPTED = unchecked ((int)0x80131519L);
1453 const int COR_E_THREADSTATE = unchecked ((int)0x80131520L);
1454 //const int COR_E_THREADSTOP = unchecked ((int)0x80131521L);
1455 const int COR_E_TYPEINITIALIZATION = unchecked ((int)0x80131534L);
1456 const int COR_E_VERIFICATION = unchecked ((int)0x8013150DL);
1457 //const int COR_E_WEAKREFERENCE = unchecked ((int)?);
1458 //const int COR_E_VTABLECALLSNOTSUPPORTED = unchecked ((int));
1460 switch (errorCode) {
1461 case MSEE_E_APPDOMAINUNLOADED:
1462 return new AppDomainUnloadedException ();
1463 case COR_E_APPLICATION:
1464 return new ApplicationException ();
1466 return new ArgumentException ();
1467 case COR_E_ARGUMENTOUTOFRANGE:
1468 return new ArgumentOutOfRangeException ();
1469 case COR_E_ARITHMETIC:
1470 return new ArithmeticException ();
1471 case COR_E_ARRAYTYPEMISMATCH:
1472 return new ArrayTypeMismatchException ();
1473 case COR_E_BADIMAGEFORMAT:
1474 case ERROR_BAD_FORMAT:
1475 return new BadImageFormatException ();
1476 // case COR_E_COMEMULATE_ERROR:
1477 // return new COMEmulateException ();
1478 case COR_E_CONTEXTMARSHAL:
1479 return new ContextMarshalException ();
1481 // return new CoreException ();
1483 return new System.Security.Cryptography.CryptographicException ();
1484 case COR_E_DIRECTORYNOTFOUND:
1485 case ERROR_PATH_NOT_FOUND:
1486 return new System.IO.DirectoryNotFoundException ();
1487 case COR_E_DIVIDEBYZERO:
1488 return new DivideByZeroException ();
1489 case COR_E_DUPLICATEWAITOBJECT:
1490 return new DuplicateWaitObjectException ();
1491 case COR_E_ENDOFSTREAM:
1492 return new System.IO.EndOfStreamException ();
1493 case COR_E_EXCEPTION:
1494 return new Exception ();
1495 case COR_E_EXECUTIONENGINE:
1496 return new ExecutionEngineException ();
1497 case COR_E_FIELDACCESS:
1498 return new FieldAccessException ();
1499 case COR_E_FILENOTFOUND:
1500 case ERROR_FILE_NOT_FOUND:
1501 return new System.IO.FileNotFoundException ();
1503 return new FormatException ();
1504 case COR_E_INDEXOUTOFRANGE:
1505 return new IndexOutOfRangeException ();
1506 case COR_E_INVALIDCAST:
1507 // E_NOINTERFACE has same value as COR_E_INVALIDCAST
1508 return new InvalidCastException ();
1509 case COR_E_INVALIDCOMOBJECT:
1510 return new InvalidComObjectException ();
1511 case COR_E_INVALIDFILTERCRITERIA:
1512 return new InvalidFilterCriteriaException ();
1513 case COR_E_INVALIDOLEVARIANTTYPE:
1514 return new InvalidOleVariantTypeException ();
1515 case COR_E_INVALIDOPERATION:
1516 return new InvalidOperationException ();
1518 return new System.IO.IOException ();
1519 case COR_E_MEMBERACCESS:
1520 return new MemberAccessException ();
1521 case COR_E_METHODACCESS:
1522 return new MethodAccessException ();
1523 case COR_E_MISSINGFIELD:
1524 return new MissingFieldException ();
1525 case COR_E_MISSINGMANIFESTRESOURCE:
1526 return new System.Resources.MissingManifestResourceException ();
1527 case COR_E_MISSINGMEMBER:
1528 return new MissingMemberException ();
1529 case COR_E_MISSINGMETHOD:
1530 return new MissingMethodException ();
1531 case COR_E_MULTICASTNOTSUPPORTED:
1532 return new MulticastNotSupportedException ();
1533 case COR_E_NOTFINITENUMBER:
1534 return new NotFiniteNumberException ();
1536 return new NotImplementedException ();
1537 case COR_E_NOTSUPPORTED:
1538 return new NotSupportedException ();
1539 case COR_E_NULLREFERENCE:
1540 // E_POINTER has the same value as COR_E_NULLREFERENCE
1541 return new NullReferenceException ();
1543 // COR_E_OUTOFMEMORY has the same value as E_OUTOFMEMORY
1544 return new OutOfMemoryException ();
1545 case COR_E_OVERFLOW:
1546 return new OverflowException ();
1547 case COR_E_PATHTOOLONG:
1548 case ERROR_FILENAME_EXCED_RANGE:
1549 return new System.IO.PathTooLongException ();
1551 return new RankException ();
1552 case COR_E_REFLECTIONTYPELOAD:
1553 return new System.Reflection.ReflectionTypeLoadException (new Type[] { }, new Exception[] { });
1554 case COR_E_REMOTING:
1555 return new System.Runtime.Remoting.RemotingException ();
1556 case COR_E_SAFEARRAYTYPEMISMATCH:
1557 return new SafeArrayTypeMismatchException ();
1558 case COR_E_SECURITY:
1559 return new SecurityException ();
1560 case COR_E_SERIALIZATION:
1561 return new System.Runtime.Serialization.SerializationException ();
1562 case COR_E_STACKOVERFLOW:
1563 case ERROR_STACK_OVERFLOW:
1564 return new StackOverflowException ();
1565 case COR_E_SYNCHRONIZATIONLOCK:
1566 return new SynchronizationLockException ();
1568 return new SystemException ();
1570 return new TargetException ();
1571 case COR_E_TARGETINVOCATION:
1572 return new System.Reflection.TargetInvocationException (null);
1573 case COR_E_TARGETPARAMCOUNT:
1574 return new TargetParameterCountException ();
1575 // case COR_E_THREADABORTED:
1576 // ThreadAbortException c'tor is inaccessible
1577 // return new System.Threading.ThreadAbortException ();
1578 case COR_E_THREADINTERRUPTED:
1579 return new ThreadInterruptedException ();
1580 case COR_E_THREADSTATE:
1581 return new ThreadStateException ();
1582 // case COR_E_THREADSTOP:
1583 // ThreadStopException does not exist
1584 // return new System.Threading.ThreadStopException ();
1585 case COR_E_TYPELOAD:
1586 return new TypeLoadException ();
1587 // MSDN lists COR_E_TYPELOAD twice with different exceptions.
1588 // return new EntryPointNotFoundException ();
1589 case COR_E_TYPEINITIALIZATION:
1590 return new TypeInitializationException("", null);
1591 case COR_E_VERIFICATION:
1592 return new VerificationException ();
1593 // case COR_E_WEAKREFERENCE:
1594 // return new WeakReferenceException ();
1595 // case COR_E_VTABLECALLSNOTSUPPORTED:
1596 // return new VTableCallsNotSupportedException ();
1599 return new COMException ("", errorCode);
1603 #if FEATURE_COMINTEROP
1604 [DllImport ("oleaut32.dll", CharSet=CharSet.Unicode, EntryPoint = "SetErrorInfo")]
1605 static extern int _SetErrorInfo (int dwReserved,
1606 [MarshalAs(UnmanagedType.Interface)] IErrorInfo pIErrorInfo);
1608 [DllImport ("oleaut32.dll", CharSet=CharSet.Unicode, EntryPoint = "GetErrorInfo")]
1609 static extern int _GetErrorInfo (int dwReserved,
1610 [MarshalAs(UnmanagedType.Interface)] out IErrorInfo ppIErrorInfo);
1612 static bool SetErrorInfoNotAvailable;
1613 static bool GetErrorInfoNotAvailable;
1615 internal static int SetErrorInfo (int dwReserved, IErrorInfo errorInfo)
1620 if (SetErrorInfoNotAvailable)
1624 retVal = _SetErrorInfo (dwReserved, errorInfo);
1627 // ignore any exception - probably there's no suitable SetErrorInfo
1628 // method available.
1629 SetErrorInfoNotAvailable = true;
1634 internal static int GetErrorInfo (int dwReserved, out IErrorInfo errorInfo)
1639 if (GetErrorInfoNotAvailable)
1643 retVal = _GetErrorInfo (dwReserved, out errorInfo);
1646 // ignore any exception - probably there's no suitable GetErrorInfo
1647 // method available.
1648 GetErrorInfoNotAvailable = true;
1653 public static Exception GetExceptionForHR (int errorCode)
1655 return GetExceptionForHR (errorCode, IntPtr.Zero);
1658 public static Exception GetExceptionForHR (int errorCode, IntPtr errorInfo)
1660 #if FEATURE_COMINTEROP
1661 IErrorInfo info = null;
1662 if (errorInfo != (IntPtr)(-1)) {
1663 if (errorInfo == IntPtr.Zero) {
1664 if (GetErrorInfo (0, out info) != 0) {
1668 info = Marshal.GetObjectForIUnknown (errorInfo) as IErrorInfo;
1672 if (info is ManagedErrorInfo && ((ManagedErrorInfo) info).Exception._HResult == errorCode) {
1673 return ((ManagedErrorInfo) info).Exception;
1676 Exception e = ConvertHrToException (errorCode);
1677 if (info != null && e != null) {
1679 info.GetHelpContext (out helpContext);
1681 info.GetSource (out str);
1683 info.GetDescription (out str);
1685 info.GetHelpFile (out str);
1687 if (helpContext == 0) {
1690 e.HelpLink = string.Format ("{0}#{1}", str, helpContext);
1695 return ConvertHrToException (errorCode);
1699 public static int FinalReleaseComObject (object o)
1701 while (ReleaseComObject (o) != 0);
1705 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1706 private static extern Delegate GetDelegateForFunctionPointerInternal (IntPtr ptr, Type t);
1708 public static Delegate GetDelegateForFunctionPointer (IntPtr ptr, Type t)
1711 throw new ArgumentNullException ("t");
1712 if (!t.IsSubclassOf (typeof (MulticastDelegate)) || (t == typeof (MulticastDelegate)))
1713 throw new ArgumentException ("Type is not a delegate", "t");
1714 if (t.IsGenericType)
1715 throw new ArgumentException ("The specified Type must not be a generic type definition.");
1716 if (ptr == IntPtr.Zero)
1717 throw new ArgumentNullException ("ptr");
1719 return GetDelegateForFunctionPointerInternal (ptr, t);
1722 public static TDelegate GetDelegateForFunctionPointer<TDelegate> (IntPtr ptr) {
1723 return (TDelegate) (object) GetDelegateForFunctionPointer (ptr, typeof (TDelegate));
1726 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1727 private static extern IntPtr GetFunctionPointerForDelegateInternal (Delegate d);
1729 public static IntPtr GetFunctionPointerForDelegate (Delegate d)
1732 throw new ArgumentNullException ("d");
1734 return GetFunctionPointerForDelegateInternal (d);
1737 public static IntPtr GetFunctionPointerForDelegate<TDelegate> (TDelegate d) {
1739 throw new ArgumentNullException ("d");
1741 return GetFunctionPointerForDelegateInternal ((Delegate)(object)d);
1744 internal static void SetLastWin32Error (int error)
1748 // Copied from referencesource/mscorlib/system/runtime/interopservices/marshal.cs
1749 //====================================================================
1750 // return the raw IUnknown* for a COM Object not related to current
1752 // Does not call AddRef
1753 //====================================================================
1754 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1755 internal static extern IntPtr /* IUnknown* */ GetRawIUnknownForComObjectNoAddRef(Object o);
1757 // Copied from referencesource/mscorlib/system/runtime/interopservices/marshal.cs
1758 //====================================================================
1759 // Converts the CLR exception to an HRESULT. This function also sets
1760 // up an IErrorInfo for the exception.
1761 // This function is only used in WinRT and converts ObjectDisposedException
1763 //====================================================================
1764 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1765 internal static extern int GetHRForException_WinRT(Exception e);
1767 // Copied from referencesource/mscorlib/system/runtime/interopservices/marshal.cs
1768 //========================================================================
1769 // Create activation factory and wraps it with a unique RCW
1770 //========================================================================
1771 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1772 internal static extern object GetNativeActivationFactory(Type type);