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;
41 using System.Runtime.ConstrainedExecution;
43 using System.Runtime.InteropServices.ComTypes;
47 namespace System.Runtime.InteropServices
49 public static class Marshal
52 public static readonly int SystemMaxDBCSCharSize = 2; // don't know what this is
53 public static readonly int SystemDefaultCharSize = Environment.IsRunningOnWindows ? 2 : 1;
56 [MethodImplAttribute (MethodImplOptions.InternalCall)]
57 private extern static int AddRefInternal (IntPtr pUnk);
60 public static int AddRef (IntPtr pUnk)
63 if (pUnk == IntPtr.Zero)
64 throw new ArgumentException ("Value cannot be null.", "pUnk");
65 return AddRefInternal (pUnk);
67 throw new NotImplementedException ();
71 [MethodImplAttribute(MethodImplOptions.InternalCall)]
72 public extern static IntPtr AllocCoTaskMem (int cb);
74 [MethodImplAttribute(MethodImplOptions.InternalCall)]
75 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
76 public extern static IntPtr AllocHGlobal (IntPtr cb);
78 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
79 public static IntPtr AllocHGlobal (int cb)
81 return AllocHGlobal ((IntPtr)cb);
85 public static object BindToMoniker (string monikerName)
87 throw new NotImplementedException ();
91 public static void ChangeWrapperHandleStrength (object otp, bool fIsWeak)
93 throw new NotImplementedException ();
96 [MethodImplAttribute(MethodImplOptions.InternalCall)]
97 internal extern static void copy_to_unmanaged (Array source, int startIndex,
98 IntPtr destination, int length);
100 [MethodImplAttribute(MethodImplOptions.InternalCall)]
101 internal extern static void copy_from_unmanaged (IntPtr source, int startIndex,
102 Array destination, int length);
104 public static void Copy (byte[] source, int startIndex, IntPtr destination, int length)
106 copy_to_unmanaged (source, startIndex, destination, length);
109 public static void Copy (char[] source, int startIndex, IntPtr destination, int length)
111 copy_to_unmanaged (source, startIndex, destination, length);
114 public static void Copy (short[] source, int startIndex, IntPtr destination, int length)
116 copy_to_unmanaged (source, startIndex, destination, length);
119 public static void Copy (int[] source, int startIndex, IntPtr destination, int length)
121 copy_to_unmanaged (source, startIndex, destination, length);
124 public static void Copy (long[] source, int startIndex, IntPtr destination, int length)
126 copy_to_unmanaged (source, startIndex, destination, length);
129 public static void Copy (float[] source, int startIndex, IntPtr destination, int length)
131 copy_to_unmanaged (source, startIndex, destination, length);
134 public static void Copy (double[] source, int startIndex, IntPtr destination, int length)
136 copy_to_unmanaged (source, startIndex, destination, length);
139 public static void Copy (IntPtr[] source, int startIndex, IntPtr destination, int length)
141 copy_to_unmanaged (source, startIndex, destination, length);
144 public static void Copy (IntPtr source, byte[] destination, int startIndex, int length)
146 copy_from_unmanaged (source, startIndex, destination, length);
149 public static void Copy (IntPtr source, char[] destination, int startIndex, int length)
151 copy_from_unmanaged (source, startIndex, destination, length);
154 public static void Copy (IntPtr source, short[] destination, int startIndex, int length)
156 copy_from_unmanaged (source, startIndex, destination, length);
159 public static void Copy (IntPtr source, int[] destination, int startIndex, int length)
161 copy_from_unmanaged (source, startIndex, destination, length);
164 public static void Copy (IntPtr source, long[] destination, int startIndex, int length)
166 copy_from_unmanaged (source, startIndex, destination, length);
169 public static void Copy (IntPtr source, float[] destination, int startIndex, int length)
171 copy_from_unmanaged (source, startIndex, destination, length);
174 public static void Copy (IntPtr source, double[] destination, int startIndex, int length)
176 copy_from_unmanaged (source, startIndex, destination, length);
179 public static void Copy (IntPtr source, IntPtr[] destination, int startIndex, int length)
181 copy_from_unmanaged (source, startIndex, destination, length);
184 public static IntPtr CreateAggregatedObject (IntPtr pOuter,
187 throw new NotImplementedException ();
191 public static IntPtr CreateAggregatedObject<T> (IntPtr pOuter, T o) {
192 return CreateAggregatedObject (pOuter, (object)o);
196 #if !FULL_AOT_RUNTIME
197 public static object CreateWrapperOfType (object o, Type t)
199 __ComObject co = o as __ComObject;
201 throw new ArgumentException ("o must derive from __ComObject", "o");
203 throw new ArgumentNullException ("t");
205 Type[] itfs = o.GetType ().GetInterfaces ();
206 foreach (Type itf in itfs) {
207 if (itf.IsImport && co.GetInterface (itf) == IntPtr.Zero)
208 throw new InvalidCastException ();
211 return ComInteropProxy.GetProxy (co.IUnknown, t).GetTransparentProxy ();
215 public static TWrapper CreateWrapperOfType<T, TWrapper> (T o) {
216 return (TWrapper)CreateWrapperOfType ((object)o, typeof (TWrapper));
221 [MethodImplAttribute(MethodImplOptions.InternalCall)]
223 public extern static void DestroyStructure (IntPtr ptr, Type structuretype);
226 public static void DestroyStructure<T> (IntPtr ptr) {
227 DestroyStructure (ptr, typeof (T));
231 [MethodImplAttribute(MethodImplOptions.InternalCall)]
232 public extern static void FreeBSTR (IntPtr ptr);
234 [MethodImplAttribute(MethodImplOptions.InternalCall)]
235 public extern static void FreeCoTaskMem (IntPtr ptr);
237 [MethodImplAttribute(MethodImplOptions.InternalCall)]
238 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
239 public extern static void FreeHGlobal (IntPtr hglobal);
241 static void ClearBSTR (IntPtr ptr)
243 int len = ReadInt32 (ptr, -4);
245 for (int i = 0; i < len; i++)
246 WriteByte (ptr, i, 0);
249 public static void ZeroFreeBSTR (IntPtr s)
255 static void ClearAnsi (IntPtr ptr)
257 for (int i = 0; ReadByte (ptr, i) != 0; i++)
258 WriteByte (ptr, i, 0);
261 static void ClearUnicode (IntPtr ptr)
263 for (int i = 0; ReadInt16 (ptr, i) != 0; i += 2)
264 WriteInt16 (ptr, i, 0);
267 public static void ZeroFreeCoTaskMemAnsi (IntPtr s)
273 public static void ZeroFreeCoTaskMemUnicode (IntPtr s)
279 public static void ZeroFreeGlobalAllocAnsi (IntPtr s)
285 public static void ZeroFreeGlobalAllocUnicode (IntPtr s)
291 #if !FULL_AOT_RUNTIME
292 public static Guid GenerateGuidForType (Type type)
297 public static string GenerateProgIdForType (Type type)
299 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (type);
301 foreach (var a in attrs)
303 var dt = a.Constructor.DeclaringType;
304 string name = dt.Name;
305 if (name == "ProgIdAttribute")
307 var args = a.ConstructorArguments;
308 string text = a.ConstructorArguments[0].Value as string;
317 return type.FullName;
321 public static object GetActiveObject (string progID)
323 throw new NotImplementedException ();
327 [MethodImplAttribute (MethodImplOptions.InternalCall)]
328 private extern static IntPtr GetCCW (object o, Type T);
330 private static IntPtr GetComInterfaceForObjectInternal (object o, Type T)
333 return ((__ComObject)o).GetInterface (T);
335 return GetCCW (o, T);
339 public static IntPtr GetComInterfaceForObject (object o, Type T)
342 IntPtr pItf = GetComInterfaceForObjectInternal (o, T);
346 throw new NotImplementedException ();
351 public static IntPtr GetComInterfaceForObject<T, TInterface> (T o) {
352 return GetComInterfaceForObject ((object)o, typeof (T));
357 public static IntPtr GetComInterfaceForObjectInContext (object o, Type t)
359 throw new NotImplementedException ();
362 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
363 public static object GetComObjectData (object obj, object key)
365 throw new NotSupportedException ("MSDN states user code should never need to call this method.");
369 [MethodImplAttribute(MethodImplOptions.InternalCall)]
370 private extern static int GetComSlotForMethodInfoInternal (MemberInfo m);
373 public static int GetComSlotForMethodInfo (MemberInfo m)
377 throw new ArgumentNullException ("m");
378 if (!(m is MethodInfo))
379 throw new ArgumentException ("The MemberInfo must be an interface method.", "m");
380 if (!m.DeclaringType.IsInterface)
381 throw new ArgumentException ("The MemberInfo must be an interface method.", "m");
382 return GetComSlotForMethodInfoInternal (m);
384 throw new NotImplementedException ();
389 public static int GetEndComSlot (Type t)
391 throw new NotImplementedException ();
395 public static int GetExceptionCode()
397 throw new NotImplementedException ();
402 public static IntPtr GetExceptionPointers()
404 throw new NotImplementedException ();
407 public static IntPtr GetHINSTANCE (Module m)
410 throw new ArgumentNullException ("m");
412 return m.GetHINSTANCE ();
414 #endif // !FULL_AOT_RUNTIME
416 #if !FULL_AOT_RUNTIME
417 public static int GetHRForException (Exception e)
419 var errorInfo = new ManagedErrorInfo(e);
420 SetErrorInfo (0, errorInfo);
426 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
427 public static int GetHRForLastWin32Error()
429 throw new NotImplementedException ();
432 [MethodImplAttribute (MethodImplOptions.InternalCall)]
433 private extern static IntPtr GetIDispatchForObjectInternal (object o);
435 public static IntPtr GetIDispatchForObject (object o)
437 IntPtr pUnk = GetIDispatchForObjectInternal (o);
438 // Internal method does not AddRef
444 public static IntPtr GetIDispatchForObjectInContext (object o)
446 throw new NotImplementedException ();
450 public static IntPtr GetITypeInfoForType (Type t)
452 throw new NotImplementedException ();
455 [MethodImplAttribute (MethodImplOptions.InternalCall)]
456 private extern static IntPtr GetIUnknownForObjectInternal (object o);
458 public static IntPtr GetIUnknownForObject (object o)
460 IntPtr pUnk = GetIUnknownForObjectInternal (o);
461 // Internal method does not AddRef
467 public static IntPtr GetIUnknownForObjectInContext (object o)
469 throw new NotImplementedException ();
473 [Obsolete ("This method has been deprecated")]
474 public static IntPtr GetManagedThunkForUnmanagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
476 throw new NotImplementedException ();
480 public static MemberInfo GetMethodInfoForComSlot (Type t, int slot, ref ComMemberType memberType)
482 throw new NotImplementedException ();
485 public static void GetNativeVariantForObject (object obj, IntPtr pDstNativeVariant)
487 Variant vt = new Variant();
489 Marshal.StructureToPtr(vt, pDstNativeVariant, false);
493 public static void GetNativeVariantForObject<T> (T obj, IntPtr pDstNativeVariant) {
494 GetNativeVariantForObject ((object)obj, pDstNativeVariant);
499 [MethodImplAttribute (MethodImplOptions.InternalCall)]
500 private static extern object GetObjectForCCW (IntPtr pUnk);
503 public static object GetObjectForIUnknown (IntPtr pUnk)
506 object obj = GetObjectForCCW (pUnk);
509 ComInteropProxy proxy = ComInteropProxy.GetProxy (pUnk, typeof (__ComObject));
510 obj = proxy.GetTransparentProxy ();
514 throw new NotImplementedException ();
518 public static object GetObjectForNativeVariant (IntPtr pSrcNativeVariant)
520 Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
521 return vt.GetValue();
525 public static T GetObjectForNativeVariant<T> (IntPtr pSrcNativeVariant) {
526 Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
527 return (T)vt.GetValue();
531 public static object[] GetObjectsForNativeVariants (IntPtr aSrcNativeVariant, int cVars)
534 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
535 object[] objects = new object[cVars];
536 for (int i = 0; i < cVars; i++)
537 objects[i] = GetObjectForNativeVariant ((IntPtr)(aSrcNativeVariant.ToInt64 () +
538 i * SizeOf (typeof(Variant))));
543 public static T[] GetObjectsForNativeVariants<T> (IntPtr aSrcNativeVariant, int cVars) {
545 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
546 T[] objects = new T[cVars];
547 for (int i = 0; i < cVars; i++)
548 objects[i] = GetObjectForNativeVariant<T> ((IntPtr)(aSrcNativeVariant.ToInt64 () +
549 i * SizeOf (typeof(Variant))));
555 public static int GetStartComSlot (Type t)
557 throw new NotImplementedException ();
561 [Obsolete ("This method has been deprecated")]
562 public static Thread GetThreadFromFiberCookie (int cookie)
564 throw new NotImplementedException ();
567 public static object GetTypedObjectForIUnknown (IntPtr pUnk, Type t)
569 ComInteropProxy proxy = new ComInteropProxy (pUnk, t);
570 __ComObject co = (__ComObject)proxy.GetTransparentProxy ();
571 foreach (Type itf in t.GetInterfaces ()) {
572 if ((itf.Attributes & TypeAttributes.Import) == TypeAttributes.Import) {
573 if (co.GetInterface (itf) == IntPtr.Zero)
581 public static Type GetTypeForITypeInfo (IntPtr piTypeInfo)
583 throw new NotImplementedException ();
586 #if !FULL_AOT_RUNTIME
589 public static string GetTypeInfoName (UCOMITypeInfo pTI)
591 throw new NotImplementedException ();
594 public static string GetTypeInfoName (ITypeInfo typeInfo)
596 throw new NotImplementedException ();
601 public static Guid GetTypeLibGuid (UCOMITypeLib pTLB)
603 throw new NotImplementedException ();
607 public static Guid GetTypeLibGuid (ITypeLib typelib)
609 throw new NotImplementedException ();
613 public static Guid GetTypeLibGuidForAssembly (Assembly asm)
615 throw new NotImplementedException ();
620 public static int GetTypeLibLcid (UCOMITypeLib pTLB)
622 throw new NotImplementedException ();
626 public static int GetTypeLibLcid (ITypeLib typelib)
628 throw new NotImplementedException ();
633 public static string GetTypeLibName (UCOMITypeLib pTLB)
635 throw new NotImplementedException ();
639 public static string GetTypeLibName (ITypeLib typelib)
641 throw new NotImplementedException ();
645 public static void GetTypeLibVersionForAssembly (Assembly inputAssembly, out int majorVersion, out int minorVersion)
647 throw new NotImplementedException ();
650 public static object GetUniqueObjectForIUnknown (IntPtr unknown)
652 throw new NotImplementedException ();
657 [Obsolete ("This method has been deprecated")]
658 public static IntPtr GetUnmanagedThunkForManagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
660 throw new NotImplementedException ();
664 [MethodImplAttribute (MethodImplOptions.InternalCall)]
665 public extern static bool IsComObject (object o);
667 public static bool IsComObject (object o)
669 throw new NotImplementedException ();
674 public static bool IsTypeVisibleFromCom (Type t)
676 throw new NotImplementedException ();
680 public static int NumParamBytes (MethodInfo m)
682 throw new NotImplementedException ();
686 [MethodImplAttribute(MethodImplOptions.InternalCall)]
687 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
688 public static extern int GetLastWin32Error();
690 [MethodImplAttribute(MethodImplOptions.InternalCall)]
691 public extern static IntPtr OffsetOf (Type t, string fieldName);
694 public static IntPtr OffsetOf<T> (string fieldName) {
695 return OffsetOf (typeof (T), fieldName);
699 [MethodImplAttribute(MethodImplOptions.InternalCall)]
700 public extern static void Prelink (MethodInfo m);
702 [MethodImplAttribute(MethodImplOptions.InternalCall)]
703 public extern static void PrelinkAll (Type c);
705 [MethodImplAttribute(MethodImplOptions.InternalCall)]
706 public extern static string PtrToStringAnsi (IntPtr ptr);
708 [MethodImplAttribute(MethodImplOptions.InternalCall)]
709 public extern static string PtrToStringAnsi (IntPtr ptr, int len);
711 public static string PtrToStringAuto (IntPtr ptr)
713 return SystemDefaultCharSize == 2
714 ? PtrToStringUni (ptr) : PtrToStringAnsi (ptr);
717 public static string PtrToStringAuto (IntPtr ptr, int len)
719 return SystemDefaultCharSize == 2
720 ? PtrToStringUni (ptr, len) : PtrToStringAnsi (ptr, len);
723 [MethodImplAttribute(MethodImplOptions.InternalCall)]
724 public extern static string PtrToStringUni (IntPtr ptr);
726 [MethodImplAttribute(MethodImplOptions.InternalCall)]
727 public extern static string PtrToStringUni (IntPtr ptr, int len);
730 [MethodImplAttribute(MethodImplOptions.InternalCall)]
731 public extern static string PtrToStringBSTR (IntPtr ptr);
733 public static string PtrToStringBSTR (IntPtr ptr)
735 throw new NotImplementedException ();
739 [MethodImplAttribute(MethodImplOptions.InternalCall)]
741 public extern static void PtrToStructure (IntPtr ptr, object structure);
743 [MethodImplAttribute(MethodImplOptions.InternalCall)]
745 public extern static object PtrToStructure (IntPtr ptr, Type structureType);
748 public static void PtrToStructure<T> (IntPtr ptr, T structure) {
749 PtrToStructure (ptr, (object)structure);
752 public static T PtrToStructure<T> (IntPtr ptr) {
753 return (T) PtrToStructure (ptr, typeof (T));
758 [MethodImplAttribute (MethodImplOptions.InternalCall)]
759 private extern static int QueryInterfaceInternal (IntPtr pUnk, ref Guid iid, out IntPtr ppv);
762 public static int QueryInterface (IntPtr pUnk, ref Guid iid, out IntPtr ppv)
765 if (pUnk == IntPtr.Zero)
766 throw new ArgumentException ("Value cannot be null.", "pUnk");
767 return QueryInterfaceInternal (pUnk, ref iid, out ppv);
769 throw new NotImplementedException ();
773 public static byte ReadByte (IntPtr ptr)
780 public static byte ReadByte (IntPtr ptr, int ofs) {
782 return *((byte*)ptr + ofs);
787 [SuppressUnmanagedCodeSecurity]
788 public static byte ReadByte ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
790 throw new NotImplementedException ();
793 public unsafe static short ReadInt16 (IntPtr ptr)
795 byte *addr = (byte *) ptr;
797 // The mono JIT can't inline this due to the hight number of calls
798 // return ReadInt16 (ptr, 0);
800 if (((uint)addr & 1) == 0)
801 return *(short*)addr;
804 String.memcpy ((byte*)&s, (byte*)ptr, 2);
808 public unsafe static short ReadInt16 (IntPtr ptr, int ofs)
810 byte *addr = ((byte *) ptr) + ofs;
812 if (((uint) addr & 1) == 0)
813 return *(short*)addr;
816 String.memcpy ((byte*)&s, addr, 2);
821 [SuppressUnmanagedCodeSecurity]
822 public static short ReadInt16 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
824 throw new NotImplementedException ();
827 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
828 public unsafe static int ReadInt32 (IntPtr ptr)
830 byte *addr = (byte *) ptr;
832 if (((uint)addr & 3) == 0)
836 String.memcpy ((byte*)&s, addr, 4);
840 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
841 public unsafe static int ReadInt32 (IntPtr ptr, int ofs)
843 byte *addr = ((byte *) ptr) + ofs;
845 if ((((int) addr) & 3) == 0)
849 String.memcpy ((byte*)&s, addr, 4);
854 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
856 [SuppressUnmanagedCodeSecurity]
857 public static int ReadInt32 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
859 throw new NotImplementedException ();
862 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
863 public unsafe static long ReadInt64 (IntPtr ptr)
865 byte *addr = (byte *) ptr;
867 // The real alignment might be 4 on some platforms, but this is just an optimization,
868 // so it doesn't matter.
869 if (((uint) addr & 7) == 0)
873 String.memcpy ((byte*)&s, addr, 8);
877 public unsafe static long ReadInt64 (IntPtr ptr, int ofs)
879 byte *addr = ((byte *) ptr) + ofs;
881 if (((uint) addr & 7) == 0)
885 String.memcpy ((byte*)&s, addr, 8);
889 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
891 [SuppressUnmanagedCodeSecurity]
892 public static long ReadInt64 ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
894 throw new NotImplementedException ();
897 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
898 public static IntPtr ReadIntPtr (IntPtr ptr)
900 if (IntPtr.Size == 4)
901 return (IntPtr)ReadInt32 (ptr);
903 return (IntPtr)ReadInt64 (ptr);
906 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
907 public static IntPtr ReadIntPtr (IntPtr ptr, int ofs)
909 if (IntPtr.Size == 4)
910 return (IntPtr)ReadInt32 (ptr, ofs);
912 return (IntPtr)ReadInt64 (ptr, ofs);
915 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
917 public static IntPtr ReadIntPtr ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
919 throw new NotImplementedException ();
922 [MethodImplAttribute (MethodImplOptions.InternalCall)]
923 public extern static IntPtr ReAllocCoTaskMem (IntPtr pv, int cb);
925 [MethodImplAttribute(MethodImplOptions.InternalCall)]
926 public extern static IntPtr ReAllocHGlobal (IntPtr pv, IntPtr cb);
929 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
930 [MethodImplAttribute (MethodImplOptions.InternalCall)]
931 private extern static int ReleaseInternal (IntPtr pUnk);
934 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
935 public static int Release (IntPtr pUnk)
938 if (pUnk == IntPtr.Zero)
939 throw new ArgumentException ("Value cannot be null.", "pUnk");
941 return ReleaseInternal (pUnk);
943 throw new NotImplementedException ();
947 #if !FULL_AOT_RUNTIME
948 [MethodImplAttribute (MethodImplOptions.InternalCall)]
949 private extern static int ReleaseComObjectInternal (object co);
951 public static int ReleaseComObject (object o)
954 throw new ArgumentException ("Value cannot be null.", "o");
955 if (!IsComObject (o))
956 throw new ArgumentException ("Value must be a Com object.", "o");
957 return ReleaseComObjectInternal (o);
962 public static void ReleaseThreadCache()
964 throw new NotImplementedException ();
967 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
968 public static bool SetComObjectData (object obj, object key, object data)
970 throw new NotSupportedException ("MSDN states user code should never need to call this method.");
975 public static int SizeOf (object structure)
977 return SizeOf (structure.GetType ());
980 [MethodImplAttribute(MethodImplOptions.InternalCall)]
981 public extern static int SizeOf (Type t);
984 public static int SizeOf<T> () {
985 return SizeOf (typeof (T));
988 public static int SizeOf<T> (T structure) {
989 return SizeOf (structure.GetType ());
993 [MethodImplAttribute(MethodImplOptions.InternalCall)]
994 public extern static IntPtr StringToBSTR (string s);
997 // I believe this is wrong, because in Mono and in P/Invoke
998 // we treat "Ansi" conversions as UTF-8 conversions, while
999 // this one does not do this
1001 public static IntPtr StringToCoTaskMemAnsi (string s)
1003 int length = s.Length + 1;
1004 IntPtr ctm = AllocCoTaskMem (length);
1006 byte[] asBytes = new byte[length];
1007 for (int i = 0; i < s.Length; i++)
1008 asBytes[i] = (byte)s[i];
1009 asBytes[s.Length] = 0;
1011 copy_to_unmanaged (asBytes, 0, ctm, length);
1015 public static IntPtr StringToCoTaskMemAuto (string s)
1017 return SystemDefaultCharSize == 2
1018 ? StringToCoTaskMemUni (s) : StringToCoTaskMemAnsi (s);
1021 public static IntPtr StringToCoTaskMemUni (string s)
1023 int length = s.Length + 1;
1024 IntPtr ctm = AllocCoTaskMem (length * 2);
1026 char[] asChars = new char[length];
1027 s.CopyTo (0, asChars, 0, s.Length);
1028 asChars[s.Length] = '\0';
1030 copy_to_unmanaged (asChars, 0, ctm, length);
1034 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1035 public extern static IntPtr StringToHGlobalAnsi (string s);
1037 public static IntPtr StringToHGlobalAuto (string s)
1039 return SystemDefaultCharSize == 2
1040 ? StringToHGlobalUni (s) : StringToHGlobalAnsi (s);
1043 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1044 public extern static IntPtr StringToHGlobalUni (string s);
1046 public static IntPtr SecureStringToBSTR (SecureString s)
1049 throw new ArgumentNullException ("s");
1051 IntPtr ctm = AllocCoTaskMem ((len+1) * 2 + 4);
1052 byte [] buffer = null;
1053 WriteInt32 (ctm, 0, len*2);
1055 buffer = s.GetBuffer ();
1057 for (int i = 0; i < len; i++)
1058 WriteInt16 (ctm, 4 + (i * 2), (short) ((buffer [(i*2)] << 8) | (buffer [i*2+1])));
1059 WriteInt16 (ctm, 4 + buffer.Length, 0);
1062 for (int i = buffer.Length; i > 0; ){
1067 return (IntPtr) ((long)ctm + 4);
1070 public static IntPtr SecureStringToCoTaskMemAnsi (SecureString s)
1073 throw new ArgumentNullException ("s");
1075 IntPtr ctm = AllocCoTaskMem (len + 1);
1076 byte [] copy = new byte [len+1];
1079 byte [] buffer = s.GetBuffer ();
1081 for (; i < len; i++, j += 2){
1082 copy [i] = buffer [j+1];
1087 copy_to_unmanaged (copy, 0, ctm, len+1);
1089 // Ensure that we clear the buffer.
1090 for (int i = len; i > 0; ){
1098 public static IntPtr SecureStringToCoTaskMemUnicode (SecureString s)
1101 throw new ArgumentNullException ("s");
1103 IntPtr ctm = AllocCoTaskMem (len * 2 + 2);
1104 byte [] buffer = null;
1106 buffer = s.GetBuffer ();
1107 for (int i = 0; i < len; i++)
1108 WriteInt16 (ctm, i * 2, (short) ((buffer [(i*2)] << 8) | (buffer [i*2+1])));
1109 WriteInt16 (ctm, buffer.Length, 0);
1112 for (int i = buffer.Length; i > 0; ){
1120 public static IntPtr SecureStringToGlobalAllocAnsi (SecureString s)
1123 throw new ArgumentNullException ("s");
1124 return SecureStringToCoTaskMemAnsi (s);
1127 public static IntPtr SecureStringToGlobalAllocUnicode (SecureString s)
1130 throw new ArgumentNullException ("s");
1131 return SecureStringToCoTaskMemUnicode (s);
1134 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
1136 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1137 public extern static void StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld);
1140 public static void StructureToPtr<T> (T structure, IntPtr ptr, bool fDeleteOld) {
1141 StructureToPtr ((object)structure, ptr, fDeleteOld);
1145 public static void ThrowExceptionForHR (int errorCode) {
1146 Exception ex = GetExceptionForHR (errorCode);
1151 public static void ThrowExceptionForHR (int errorCode, IntPtr errorInfo) {
1152 Exception ex = GetExceptionForHR (errorCode, errorInfo);
1157 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1158 public extern static IntPtr UnsafeAddrOfPinnedArrayElement (Array arr, int index);
1161 public static IntPtr UnsafeAddrOfPinnedArrayElement<T> (T[] arr, int index) {
1162 return UnsafeAddrOfPinnedArrayElement ((Array)arr, index);
1166 public static void WriteByte (IntPtr ptr, byte val)
1173 public static void WriteByte (IntPtr ptr, int ofs, byte val) {
1175 *(byte*)(IntPtr.Add (ptr, ofs)) = val;
1180 [SuppressUnmanagedCodeSecurity]
1181 public static void WriteByte ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, byte val)
1183 throw new NotImplementedException ();
1186 public static unsafe void WriteInt16 (IntPtr ptr, short val)
1188 byte *addr = (byte *) ptr;
1190 if (((uint)addr & 1) == 0)
1191 *(short*)addr = val;
1193 String.memcpy (addr, (byte*)&val, 2);
1196 public static unsafe void WriteInt16 (IntPtr ptr, int ofs, short val)
1198 byte *addr = ((byte *) ptr) + ofs;
1200 if (((uint)addr & 1) == 0)
1201 *(short*)addr = val;
1203 String.memcpy (addr, (byte*)&val, 2);
1208 [SuppressUnmanagedCodeSecurity]
1209 public static void WriteInt16 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, short val)
1211 throw new NotImplementedException ();
1214 public static void WriteInt16 (IntPtr ptr, char val)
1216 WriteInt16 (ptr, 0, (short)val);
1219 public static void WriteInt16 (IntPtr ptr, int ofs, char val)
1221 WriteInt16 (ptr, ofs, (short)val);
1225 public static void WriteInt16([In, Out] object ptr, int ofs, char val)
1227 throw new NotImplementedException ();
1230 public static unsafe void WriteInt32 (IntPtr ptr, int val)
1232 byte *addr = (byte *) ptr;
1234 if (((uint)addr & 3) == 0)
1237 String.memcpy (addr, (byte*)&val, 4);
1241 public unsafe static void WriteInt32 (IntPtr ptr, int ofs, int val)
1243 byte *addr = ((byte *) ptr) + ofs;
1245 if (((uint)addr & 3) == 0)
1248 String.memcpy (addr, (byte*)&val, 4);
1253 [SuppressUnmanagedCodeSecurity]
1254 public static void WriteInt32([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, int val)
1256 throw new NotImplementedException ();
1259 public static unsafe void WriteInt64 (IntPtr ptr, long val)
1261 byte *addr = (byte *) ptr;
1263 // The real alignment might be 4 on some platforms, but this is just an optimization,
1264 // so it doesn't matter.
1265 if (((uint)addr & 7) == 0)
1268 String.memcpy (addr, (byte*)&val, 8);
1271 public static unsafe void WriteInt64 (IntPtr ptr, int ofs, long val)
1273 byte *addr = ((byte *) ptr) + ofs;
1275 // The real alignment might be 4 on some platforms, but this is just an optimization,
1276 // so it doesn't matter.
1277 if (((uint)addr & 7) == 0)
1280 String.memcpy (addr, (byte*)&val, 8);
1284 [SuppressUnmanagedCodeSecurity]
1285 public static void WriteInt64 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, long val)
1287 throw new NotImplementedException ();
1290 public static void WriteIntPtr (IntPtr ptr, IntPtr val)
1292 if (IntPtr.Size == 4)
1293 WriteInt32 (ptr, (int)val);
1295 WriteInt64 (ptr, (long)val);
1298 public static void WriteIntPtr (IntPtr ptr, int ofs, IntPtr val)
1300 if (IntPtr.Size == 4)
1301 WriteInt32 (ptr, ofs, (int)val);
1303 WriteInt64 (ptr, ofs, (long)val);
1307 public static void WriteIntPtr([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, IntPtr val)
1309 throw new NotImplementedException ();
1312 private static Exception ConvertHrToException (int errorCode)
1314 const int MSEE_E_APPDOMAINUNLOADED = unchecked ((int)0x80131014L);
1315 const int COR_E_APPLICATION = unchecked ((int)0x80131600L);
1316 const int E_INVALIDARG = unchecked ((int)0x80070057);
1317 const int COR_E_ARGUMENTOUTOFRANGE = unchecked ((int)0x80131502L);
1318 const int COR_E_ARITHMETIC = unchecked ((int)0x80070216);
1319 const int COR_E_ARRAYTYPEMISMATCH = unchecked ((int)0x80131503L);
1320 const int COR_E_BADIMAGEFORMAT = unchecked ((int)0x8007000BL);
1321 const int ERROR_BAD_FORMAT = unchecked ((int)0x0B);
1322 //const int COR_E_COMEMULATE_ERROR = unchecked ((int)?);
1323 const int COR_E_CONTEXTMARSHAL = unchecked ((int)0x80131504L);
1324 //const int COR_E_CORE = unchecked ((int)?);
1325 const int NTE_FAIL = unchecked ((int)0x80090020L);
1326 const int COR_E_DIRECTORYNOTFOUND = unchecked ((int)0x80070003L);
1327 const int ERROR_PATH_NOT_FOUND = unchecked ((int)0x03);
1328 const int COR_E_DIVIDEBYZERO = unchecked ((int)0x80020012L);
1329 const int COR_E_DUPLICATEWAITOBJECT = unchecked ((int)0x80131529L);
1330 const int COR_E_ENDOFSTREAM = unchecked ((int)0x80070026L);
1331 const int COR_E_TYPELOAD = unchecked ((int)0x80131522L);
1332 const int COR_E_EXCEPTION = unchecked ((int)0x80131500L);
1333 const int COR_E_EXECUTIONENGINE = unchecked ((int)0x80131506L);
1334 const int COR_E_FIELDACCESS = unchecked ((int)0x80131507L);
1335 const int COR_E_FILENOTFOUND = unchecked ((int)0x80070002L);
1336 const int ERROR_FILE_NOT_FOUND = unchecked ((int)0x02);
1337 const int COR_E_FORMAT = unchecked ((int)0x80131537L);
1338 const int COR_E_INDEXOUTOFRANGE = unchecked ((int)0x80131508L);
1339 const int COR_E_INVALIDCAST = unchecked ((int)0x80004002L);
1340 const int COR_E_INVALIDCOMOBJECT = unchecked ((int)0x80131527L);
1341 const int COR_E_INVALIDFILTERCRITERIA = unchecked ((int)0x80131601L);
1342 const int COR_E_INVALIDOLEVARIANTTYPE = unchecked ((int)0x80131531L);
1343 const int COR_E_INVALIDOPERATION = unchecked ((int)0x80131509L);
1344 const int COR_E_IO = unchecked ((int)0x80131620L);
1345 const int COR_E_MEMBERACCESS = unchecked ((int)0x8013151AL);
1346 const int COR_E_METHODACCESS = unchecked ((int)0x80131510L);
1347 const int COR_E_MISSINGFIELD = unchecked ((int)0x80131511L);
1348 const int COR_E_MISSINGMANIFESTRESOURCE = unchecked ((int)0x80131532L);
1349 const int COR_E_MISSINGMEMBER = unchecked ((int)0x80131512L);
1350 const int COR_E_MISSINGMETHOD = unchecked ((int)0x80131513L);
1351 const int COR_E_MULTICASTNOTSUPPORTED = unchecked ((int)0x80131514L);
1352 const int COR_E_NOTFINITENUMBER = unchecked ((int)0x80131528L);
1353 const int E_NOTIMPL = unchecked ((int)0x80004001L);
1354 const int COR_E_NOTSUPPORTED = unchecked ((int)0x80131515L);
1355 const int COR_E_NULLREFERENCE = unchecked ((int)0x80004003L);
1356 const int E_OUTOFMEMORY = unchecked ((int)0x8007000EL);
1357 const int COR_E_OVERFLOW = unchecked ((int)0x80131516L);
1358 const int COR_E_PATHTOOLONG = unchecked ((int)0x800700CEL);
1359 const int ERROR_FILENAME_EXCED_RANGE = unchecked ((int)0xCE);
1360 const int COR_E_RANK = unchecked ((int)0x80131517L);
1361 const int COR_E_REFLECTIONTYPELOAD = unchecked ((int)0x80131602L);
1362 const int COR_E_REMOTING = unchecked ((int)0x8013150BL);
1363 const int COR_E_SAFEARRAYTYPEMISMATCH = unchecked ((int)0x80131533L);
1364 const int COR_E_SECURITY = unchecked ((int)0x8013150AL);
1365 const int COR_E_SERIALIZATION = unchecked ((int)0x8013150CL);
1366 const int COR_E_STACKOVERFLOW = unchecked ((int)0x800703E9L);
1367 const int ERROR_STACK_OVERFLOW = unchecked ((int)0x03E9);
1368 const int COR_E_SYNCHRONIZATIONLOCK = unchecked ((int)0x80131518L);
1369 const int COR_E_SYSTEM = unchecked ((int)0x80131501L);
1370 const int COR_E_TARGET = unchecked ((int)0x80131603L);
1371 const int COR_E_TARGETINVOCATION = unchecked ((int)0x80131604L);
1372 const int COR_E_TARGETPARAMCOUNT = unchecked ((int)0x8002000EL);
1373 const int COR_E_THREADABORTED = unchecked ((int)0x80131530L);
1374 const int COR_E_THREADINTERRUPTED = unchecked ((int)0x80131519L);
1375 const int COR_E_THREADSTATE = unchecked ((int)0x80131520L);
1376 const int COR_E_THREADSTOP = unchecked ((int)0x80131521L);
1377 const int COR_E_TYPEINITIALIZATION = unchecked ((int)0x80131534L);
1378 const int COR_E_VERIFICATION = unchecked ((int)0x8013150DL);
1379 //const int COR_E_WEAKREFERENCE = unchecked ((int)?);
1380 //const int COR_E_VTABLECALLSNOTSUPPORTED = unchecked ((int));
1382 switch (errorCode) {
1383 case MSEE_E_APPDOMAINUNLOADED:
1384 return new AppDomainUnloadedException ();
1385 case COR_E_APPLICATION:
1386 return new ApplicationException ();
1388 return new ArgumentException ();
1389 case COR_E_ARGUMENTOUTOFRANGE:
1390 return new ArgumentOutOfRangeException ();
1391 case COR_E_ARITHMETIC:
1392 return new ArithmeticException ();
1393 case COR_E_ARRAYTYPEMISMATCH:
1394 return new ArrayTypeMismatchException ();
1395 case COR_E_BADIMAGEFORMAT:
1396 case ERROR_BAD_FORMAT:
1397 return new BadImageFormatException ();
1398 // case COR_E_COMEMULATE_ERROR:
1399 // return new COMEmulateException ();
1400 case COR_E_CONTEXTMARSHAL:
1401 return new ContextMarshalException ();
1403 // return new CoreException ();
1405 return new System.Security.Cryptography.CryptographicException ();
1406 case COR_E_DIRECTORYNOTFOUND:
1407 case ERROR_PATH_NOT_FOUND:
1408 return new System.IO.DirectoryNotFoundException ();
1409 case COR_E_DIVIDEBYZERO:
1410 return new DivideByZeroException ();
1411 case COR_E_DUPLICATEWAITOBJECT:
1412 return new DuplicateWaitObjectException ();
1413 case COR_E_ENDOFSTREAM:
1414 return new System.IO.EndOfStreamException ();
1415 case COR_E_EXCEPTION:
1416 return new Exception ();
1417 case COR_E_EXECUTIONENGINE:
1418 return new ExecutionEngineException ();
1419 case COR_E_FIELDACCESS:
1420 return new FieldAccessException ();
1421 case COR_E_FILENOTFOUND:
1422 case ERROR_FILE_NOT_FOUND:
1423 return new System.IO.FileNotFoundException ();
1425 return new FormatException ();
1426 case COR_E_INDEXOUTOFRANGE:
1427 return new IndexOutOfRangeException ();
1428 case COR_E_INVALIDCAST:
1429 // E_NOINTERFACE has same value as COR_E_INVALIDCAST
1430 return new InvalidCastException ();
1431 case COR_E_INVALIDCOMOBJECT:
1432 return new InvalidComObjectException ();
1433 case COR_E_INVALIDFILTERCRITERIA:
1434 return new InvalidFilterCriteriaException ();
1435 case COR_E_INVALIDOLEVARIANTTYPE:
1436 return new InvalidOleVariantTypeException ();
1437 case COR_E_INVALIDOPERATION:
1438 return new InvalidOperationException ();
1440 return new System.IO.IOException ();
1441 case COR_E_MEMBERACCESS:
1442 return new MemberAccessException ();
1443 case COR_E_METHODACCESS:
1444 return new MethodAccessException ();
1445 case COR_E_MISSINGFIELD:
1446 return new MissingFieldException ();
1447 case COR_E_MISSINGMANIFESTRESOURCE:
1448 return new System.Resources.MissingManifestResourceException ();
1449 case COR_E_MISSINGMEMBER:
1450 return new MissingMemberException ();
1451 case COR_E_MISSINGMETHOD:
1452 return new MissingMethodException ();
1453 case COR_E_MULTICASTNOTSUPPORTED:
1454 return new MulticastNotSupportedException ();
1455 case COR_E_NOTFINITENUMBER:
1456 return new NotFiniteNumberException ();
1458 return new NotImplementedException ();
1459 case COR_E_NOTSUPPORTED:
1460 return new NotSupportedException ();
1461 case COR_E_NULLREFERENCE:
1462 // E_POINTER has the same value as COR_E_NULLREFERENCE
1463 return new NullReferenceException ();
1465 // COR_E_OUTOFMEMORY has the same value as E_OUTOFMEMORY
1466 return new OutOfMemoryException ();
1467 case COR_E_OVERFLOW:
1468 return new OverflowException ();
1469 case COR_E_PATHTOOLONG:
1470 case ERROR_FILENAME_EXCED_RANGE:
1471 return new System.IO.PathTooLongException ();
1473 return new RankException ();
1474 case COR_E_REFLECTIONTYPELOAD:
1475 return new System.Reflection.ReflectionTypeLoadException (new Type[] { }, new Exception[] { });
1476 case COR_E_REMOTING:
1477 return new System.Runtime.Remoting.RemotingException ();
1478 case COR_E_SAFEARRAYTYPEMISMATCH:
1479 return new SafeArrayTypeMismatchException ();
1480 case COR_E_SECURITY:
1481 return new SecurityException ();
1482 case COR_E_SERIALIZATION:
1483 return new System.Runtime.Serialization.SerializationException ();
1484 case COR_E_STACKOVERFLOW:
1485 case ERROR_STACK_OVERFLOW:
1486 return new StackOverflowException ();
1487 case COR_E_SYNCHRONIZATIONLOCK:
1488 return new SynchronizationLockException ();
1490 return new SystemException ();
1492 return new TargetException ();
1493 case COR_E_TARGETINVOCATION:
1494 return new System.Reflection.TargetInvocationException (null);
1495 case COR_E_TARGETPARAMCOUNT:
1496 return new TargetParameterCountException ();
1497 // case COR_E_THREADABORTED:
1498 // ThreadAbortException c'tor is inaccessible
1499 // return new System.Threading.ThreadAbortException ();
1500 case COR_E_THREADINTERRUPTED:
1501 return new ThreadInterruptedException ();
1502 case COR_E_THREADSTATE:
1503 return new ThreadStateException ();
1504 // case COR_E_THREADSTOP:
1505 // ThreadStopException does not exist
1506 // return new System.Threading.ThreadStopException ();
1507 case COR_E_TYPELOAD:
1508 return new TypeLoadException ();
1509 // MSDN lists COR_E_TYPELOAD twice with different exceptions.
1510 // return new EntryPointNotFoundException ();
1511 case COR_E_TYPEINITIALIZATION:
1512 return new TypeInitializationException("", null);
1513 case COR_E_VERIFICATION:
1514 return new VerificationException ();
1515 // case COR_E_WEAKREFERENCE:
1516 // return new WeakReferenceException ();
1517 // case COR_E_VTABLECALLSNOTSUPPORTED:
1518 // return new VTableCallsNotSupportedException ();
1521 return new COMException ("", errorCode);
1525 [DllImport ("oleaut32.dll", CharSet=CharSet.Unicode, EntryPoint = "SetErrorInfo")]
1526 static extern int _SetErrorInfo (int dwReserved,
1527 [MarshalAs(UnmanagedType.Interface)] IErrorInfo pIErrorInfo);
1529 [DllImport ("oleaut32.dll", CharSet=CharSet.Unicode, EntryPoint = "GetErrorInfo")]
1530 static extern int _GetErrorInfo (int dwReserved,
1531 [MarshalAs(UnmanagedType.Interface)] out IErrorInfo ppIErrorInfo);
1533 static bool SetErrorInfoNotAvailable;
1534 static bool GetErrorInfoNotAvailable;
1536 internal static int SetErrorInfo (int dwReserved, IErrorInfo errorInfo)
1541 if (SetErrorInfoNotAvailable)
1545 retVal = _SetErrorInfo (dwReserved, errorInfo);
1548 // ignore any exception - probably there's no suitable SetErrorInfo
1549 // method available.
1550 SetErrorInfoNotAvailable = true;
1555 internal static int GetErrorInfo (int dwReserved, out IErrorInfo errorInfo)
1560 if (GetErrorInfoNotAvailable)
1564 retVal = _GetErrorInfo (dwReserved, out errorInfo);
1567 // ignore any exception - probably there's no suitable GetErrorInfo
1568 // method available.
1569 GetErrorInfoNotAvailable = true;
1574 public static Exception GetExceptionForHR (int errorCode)
1576 return GetExceptionForHR (errorCode, IntPtr.Zero);
1579 public static Exception GetExceptionForHR (int errorCode, IntPtr errorInfoPtr)
1581 IErrorInfo errorInfo = null;
1582 if (errorInfoPtr != (IntPtr)(-1)) {
1583 if (errorInfoPtr == IntPtr.Zero) {
1584 if (GetErrorInfo (0, out errorInfo) != 0) {
1588 errorInfo = Marshal.GetObjectForIUnknown (errorInfoPtr) as IErrorInfo;
1592 if (errorInfo is ManagedErrorInfo && ((ManagedErrorInfo)errorInfo).Exception.hresult == errorCode) {
1593 return ((ManagedErrorInfo)errorInfo).Exception;
1596 Exception e = ConvertHrToException (errorCode);
1597 if (errorInfo != null && e != null) {
1599 errorInfo.GetHelpContext (out helpContext);
1601 errorInfo.GetSource (out str);
1603 errorInfo.GetDescription (out str);
1605 errorInfo.GetHelpFile (out str);
1607 if (helpContext == 0) {
1610 e.HelpLink = string.Format ("{0}#{1}", str, helpContext);
1616 #if !FULL_AOT_RUNTIME
1617 public static int FinalReleaseComObject (object o)
1619 while (ReleaseComObject (o) != 0);
1624 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1625 private static extern Delegate GetDelegateForFunctionPointerInternal (IntPtr ptr, Type t);
1627 public static Delegate GetDelegateForFunctionPointer (IntPtr ptr, Type t)
1630 throw new ArgumentNullException ("t");
1631 if (!t.IsSubclassOf (typeof (MulticastDelegate)) || (t == typeof (MulticastDelegate)))
1632 throw new ArgumentException ("Type is not a delegate", "t");
1633 if (t.IsGenericType)
1634 throw new ArgumentException ("The specified Type must not be a generic type definition.");
1635 if (ptr == IntPtr.Zero)
1636 throw new ArgumentNullException ("ptr");
1638 return GetDelegateForFunctionPointerInternal (ptr, t);
1642 public static TDelegate GetDelegateForFunctionPointer<TDelegate> (IntPtr ptr) {
1643 return (TDelegate) (object) GetDelegateForFunctionPointer (ptr, typeof (TDelegate));
1647 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1648 private static extern IntPtr GetFunctionPointerForDelegateInternal (Delegate d);
1650 public static IntPtr GetFunctionPointerForDelegate (Delegate d)
1653 throw new ArgumentNullException ("d");
1655 return GetFunctionPointerForDelegateInternal (d);
1659 public static IntPtr GetFunctionPointerForDelegate<TDelegate> (TDelegate d) {
1661 throw new ArgumentNullException ("d");
1663 return GetFunctionPointerForDelegateInternal ((Delegate)(object)d);