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 ();
587 public static Type GetTypeFromCLSID (Guid clsid)
589 throw new NotImplementedException ();
593 #if !FULL_AOT_RUNTIME
596 public static string GetTypeInfoName (UCOMITypeInfo pTI)
598 throw new NotImplementedException ();
601 public static string GetTypeInfoName (ITypeInfo typeInfo)
603 throw new NotImplementedException ();
608 public static Guid GetTypeLibGuid (UCOMITypeLib pTLB)
610 throw new NotImplementedException ();
614 public static Guid GetTypeLibGuid (ITypeLib typelib)
616 throw new NotImplementedException ();
620 public static Guid GetTypeLibGuidForAssembly (Assembly asm)
622 throw new NotImplementedException ();
627 public static int GetTypeLibLcid (UCOMITypeLib pTLB)
629 throw new NotImplementedException ();
633 public static int GetTypeLibLcid (ITypeLib typelib)
635 throw new NotImplementedException ();
640 public static string GetTypeLibName (UCOMITypeLib pTLB)
642 throw new NotImplementedException ();
646 public static string GetTypeLibName (ITypeLib typelib)
648 throw new NotImplementedException ();
652 public static void GetTypeLibVersionForAssembly (Assembly inputAssembly, out int majorVersion, out int minorVersion)
654 throw new NotImplementedException ();
657 public static object GetUniqueObjectForIUnknown (IntPtr unknown)
659 throw new NotImplementedException ();
664 [Obsolete ("This method has been deprecated")]
665 public static IntPtr GetUnmanagedThunkForManagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
667 throw new NotImplementedException ();
671 [MethodImplAttribute (MethodImplOptions.InternalCall)]
672 public extern static bool IsComObject (object o);
674 public static bool IsComObject (object o)
676 throw new NotImplementedException ();
681 public static bool IsTypeVisibleFromCom (Type t)
683 throw new NotImplementedException ();
687 public static int NumParamBytes (MethodInfo m)
689 throw new NotImplementedException ();
693 [MethodImplAttribute(MethodImplOptions.InternalCall)]
694 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
695 public static extern int GetLastWin32Error();
697 [MethodImplAttribute(MethodImplOptions.InternalCall)]
698 public extern static IntPtr OffsetOf (Type t, string fieldName);
701 public static IntPtr OffsetOf<T> (string fieldName) {
702 return OffsetOf (typeof (T), fieldName);
706 [MethodImplAttribute(MethodImplOptions.InternalCall)]
707 public extern static void Prelink (MethodInfo m);
709 [MethodImplAttribute(MethodImplOptions.InternalCall)]
710 public extern static void PrelinkAll (Type c);
712 [MethodImplAttribute(MethodImplOptions.InternalCall)]
713 public extern static string PtrToStringAnsi (IntPtr ptr);
715 [MethodImplAttribute(MethodImplOptions.InternalCall)]
716 public extern static string PtrToStringAnsi (IntPtr ptr, int len);
718 public static string PtrToStringAuto (IntPtr ptr)
720 return SystemDefaultCharSize == 2
721 ? PtrToStringUni (ptr) : PtrToStringAnsi (ptr);
724 public static string PtrToStringAuto (IntPtr ptr, int len)
726 return SystemDefaultCharSize == 2
727 ? PtrToStringUni (ptr, len) : PtrToStringAnsi (ptr, len);
730 [MethodImplAttribute(MethodImplOptions.InternalCall)]
731 public extern static string PtrToStringUni (IntPtr ptr);
733 [MethodImplAttribute(MethodImplOptions.InternalCall)]
734 public extern static string PtrToStringUni (IntPtr ptr, int len);
737 [MethodImplAttribute(MethodImplOptions.InternalCall)]
738 public extern static string PtrToStringBSTR (IntPtr ptr);
740 public static string PtrToStringBSTR (IntPtr ptr)
742 throw new NotImplementedException ();
746 [MethodImplAttribute(MethodImplOptions.InternalCall)]
748 public extern static void PtrToStructure (IntPtr ptr, object structure);
750 [MethodImplAttribute(MethodImplOptions.InternalCall)]
752 public extern static object PtrToStructure (IntPtr ptr, Type structureType);
755 public static void PtrToStructure<T> (IntPtr ptr, T structure) {
756 PtrToStructure (ptr, (object)structure);
759 public static T PtrToStructure<T> (IntPtr ptr) {
760 return (T) PtrToStructure (ptr, typeof (T));
765 [MethodImplAttribute (MethodImplOptions.InternalCall)]
766 private extern static int QueryInterfaceInternal (IntPtr pUnk, ref Guid iid, out IntPtr ppv);
769 public static int QueryInterface (IntPtr pUnk, ref Guid iid, out IntPtr ppv)
772 if (pUnk == IntPtr.Zero)
773 throw new ArgumentException ("Value cannot be null.", "pUnk");
774 return QueryInterfaceInternal (pUnk, ref iid, out ppv);
776 throw new NotImplementedException ();
780 public static byte ReadByte (IntPtr ptr)
787 public static byte ReadByte (IntPtr ptr, int ofs) {
789 return *((byte*)ptr + ofs);
794 [SuppressUnmanagedCodeSecurity]
795 public static byte ReadByte ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
797 throw new NotImplementedException ();
800 public unsafe static short ReadInt16 (IntPtr ptr)
802 byte *addr = (byte *) ptr;
804 // The mono JIT can't inline this due to the hight number of calls
805 // return ReadInt16 (ptr, 0);
807 if (((uint)addr & 1) == 0)
808 return *(short*)addr;
811 String.memcpy ((byte*)&s, (byte*)ptr, 2);
815 public unsafe static short ReadInt16 (IntPtr ptr, int ofs)
817 byte *addr = ((byte *) ptr) + ofs;
819 if (((uint) addr & 1) == 0)
820 return *(short*)addr;
823 String.memcpy ((byte*)&s, addr, 2);
828 [SuppressUnmanagedCodeSecurity]
829 public static short ReadInt16 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
831 throw new NotImplementedException ();
834 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
835 public unsafe static int ReadInt32 (IntPtr ptr)
837 byte *addr = (byte *) ptr;
839 if (((uint)addr & 3) == 0)
843 String.memcpy ((byte*)&s, addr, 4);
847 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
848 public unsafe static int ReadInt32 (IntPtr ptr, int ofs)
850 byte *addr = ((byte *) ptr) + ofs;
852 if ((((int) addr) & 3) == 0)
856 String.memcpy ((byte*)&s, addr, 4);
861 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
863 [SuppressUnmanagedCodeSecurity]
864 public static int ReadInt32 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
866 throw new NotImplementedException ();
869 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
870 public unsafe static long ReadInt64 (IntPtr ptr)
872 byte *addr = (byte *) ptr;
874 // The real alignment might be 4 on some platforms, but this is just an optimization,
875 // so it doesn't matter.
876 if (((uint) addr & 7) == 0)
880 String.memcpy ((byte*)&s, addr, 8);
884 public unsafe static long ReadInt64 (IntPtr ptr, int ofs)
886 byte *addr = ((byte *) ptr) + ofs;
888 if (((uint) addr & 7) == 0)
892 String.memcpy ((byte*)&s, addr, 8);
896 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
898 [SuppressUnmanagedCodeSecurity]
899 public static long ReadInt64 ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
901 throw new NotImplementedException ();
904 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
905 public static IntPtr ReadIntPtr (IntPtr ptr)
907 if (IntPtr.Size == 4)
908 return (IntPtr)ReadInt32 (ptr);
910 return (IntPtr)ReadInt64 (ptr);
913 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
914 public static IntPtr ReadIntPtr (IntPtr ptr, int ofs)
916 if (IntPtr.Size == 4)
917 return (IntPtr)ReadInt32 (ptr, ofs);
919 return (IntPtr)ReadInt64 (ptr, ofs);
922 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
924 public static IntPtr ReadIntPtr ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
926 throw new NotImplementedException ();
929 [MethodImplAttribute (MethodImplOptions.InternalCall)]
930 public extern static IntPtr ReAllocCoTaskMem (IntPtr pv, int cb);
932 [MethodImplAttribute(MethodImplOptions.InternalCall)]
933 public extern static IntPtr ReAllocHGlobal (IntPtr pv, IntPtr cb);
936 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
937 [MethodImplAttribute (MethodImplOptions.InternalCall)]
938 private extern static int ReleaseInternal (IntPtr pUnk);
941 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
942 public static int Release (IntPtr pUnk)
945 if (pUnk == IntPtr.Zero)
946 throw new ArgumentException ("Value cannot be null.", "pUnk");
948 return ReleaseInternal (pUnk);
950 throw new NotImplementedException ();
954 #if !FULL_AOT_RUNTIME
955 [MethodImplAttribute (MethodImplOptions.InternalCall)]
956 private extern static int ReleaseComObjectInternal (object co);
958 public static int ReleaseComObject (object o)
961 throw new ArgumentException ("Value cannot be null.", "o");
962 if (!IsComObject (o))
963 throw new ArgumentException ("Value must be a Com object.", "o");
964 return ReleaseComObjectInternal (o);
969 public static void ReleaseThreadCache()
971 throw new NotImplementedException ();
974 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
975 public static bool SetComObjectData (object obj, object key, object data)
977 throw new NotSupportedException ("MSDN states user code should never need to call this method.");
982 public static int SizeOf (object structure)
984 return SizeOf (structure.GetType ());
987 [MethodImplAttribute(MethodImplOptions.InternalCall)]
988 public extern static int SizeOf (Type t);
991 public static int SizeOf<T> () {
992 return SizeOf (typeof (T));
995 public static int SizeOf<T> (T structure) {
996 return SizeOf (structure.GetType ());
1000 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1001 public extern static IntPtr StringToBSTR (string s);
1004 // I believe this is wrong, because in Mono and in P/Invoke
1005 // we treat "Ansi" conversions as UTF-8 conversions, while
1006 // this one does not do this
1008 public static IntPtr StringToCoTaskMemAnsi (string s)
1010 int length = s.Length + 1;
1011 IntPtr ctm = AllocCoTaskMem (length);
1013 byte[] asBytes = new byte[length];
1014 for (int i = 0; i < s.Length; i++)
1015 asBytes[i] = (byte)s[i];
1016 asBytes[s.Length] = 0;
1018 copy_to_unmanaged (asBytes, 0, ctm, length);
1022 public static IntPtr StringToCoTaskMemAuto (string s)
1024 return SystemDefaultCharSize == 2
1025 ? StringToCoTaskMemUni (s) : StringToCoTaskMemAnsi (s);
1028 public static IntPtr StringToCoTaskMemUni (string s)
1030 int length = s.Length + 1;
1031 IntPtr ctm = AllocCoTaskMem (length * 2);
1033 char[] asChars = new char[length];
1034 s.CopyTo (0, asChars, 0, s.Length);
1035 asChars[s.Length] = '\0';
1037 copy_to_unmanaged (asChars, 0, ctm, length);
1041 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1042 public extern static IntPtr StringToHGlobalAnsi (string s);
1044 public static IntPtr StringToHGlobalAuto (string s)
1046 return SystemDefaultCharSize == 2
1047 ? StringToHGlobalUni (s) : StringToHGlobalAnsi (s);
1050 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1051 public extern static IntPtr StringToHGlobalUni (string s);
1053 public static IntPtr SecureStringToBSTR (SecureString s)
1056 throw new ArgumentNullException ("s");
1058 IntPtr ctm = AllocCoTaskMem ((len+1) * 2 + 4);
1059 byte [] buffer = null;
1060 WriteInt32 (ctm, 0, len*2);
1062 buffer = s.GetBuffer ();
1064 for (int i = 0; i < len; i++)
1065 WriteInt16 (ctm, 4 + (i * 2), (short) ((buffer [(i*2)] << 8) | (buffer [i*2+1])));
1066 WriteInt16 (ctm, 4 + buffer.Length, 0);
1069 for (int i = buffer.Length; i > 0; ){
1074 return (IntPtr) ((long)ctm + 4);
1077 public static IntPtr SecureStringToCoTaskMemAnsi (SecureString s)
1080 throw new ArgumentNullException ("s");
1082 IntPtr ctm = AllocCoTaskMem (len + 1);
1083 byte [] copy = new byte [len+1];
1086 byte [] buffer = s.GetBuffer ();
1088 for (; i < len; i++, j += 2){
1089 copy [i] = buffer [j+1];
1094 copy_to_unmanaged (copy, 0, ctm, len+1);
1096 // Ensure that we clear the buffer.
1097 for (int i = len; i > 0; ){
1105 public static IntPtr SecureStringToCoTaskMemUnicode (SecureString s)
1108 throw new ArgumentNullException ("s");
1110 IntPtr ctm = AllocCoTaskMem (len * 2 + 2);
1111 byte [] buffer = null;
1113 buffer = s.GetBuffer ();
1114 for (int i = 0; i < len; i++)
1115 WriteInt16 (ctm, i * 2, (short) ((buffer [(i*2)] << 8) | (buffer [i*2+1])));
1116 WriteInt16 (ctm, buffer.Length, 0);
1119 for (int i = buffer.Length; i > 0; ){
1127 public static IntPtr SecureStringToGlobalAllocAnsi (SecureString s)
1130 throw new ArgumentNullException ("s");
1131 return SecureStringToCoTaskMemAnsi (s);
1134 public static IntPtr SecureStringToGlobalAllocUnicode (SecureString s)
1137 throw new ArgumentNullException ("s");
1138 return SecureStringToCoTaskMemUnicode (s);
1141 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
1143 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1144 public extern static void StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld);
1147 public static void StructureToPtr<T> (T structure, IntPtr ptr, bool fDeleteOld) {
1148 StructureToPtr ((object)structure, ptr, fDeleteOld);
1152 public static void ThrowExceptionForHR (int errorCode) {
1153 Exception ex = GetExceptionForHR (errorCode);
1158 public static void ThrowExceptionForHR (int errorCode, IntPtr errorInfo) {
1159 Exception ex = GetExceptionForHR (errorCode, errorInfo);
1164 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1165 public extern static IntPtr UnsafeAddrOfPinnedArrayElement (Array arr, int index);
1168 public static IntPtr UnsafeAddrOfPinnedArrayElement<T> (T[] arr, int index) {
1169 return UnsafeAddrOfPinnedArrayElement ((Array)arr, index);
1173 public static void WriteByte (IntPtr ptr, byte val)
1180 public static void WriteByte (IntPtr ptr, int ofs, byte val) {
1182 *(byte*)(IntPtr.Add (ptr, ofs)) = val;
1187 [SuppressUnmanagedCodeSecurity]
1188 public static void WriteByte ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, byte val)
1190 throw new NotImplementedException ();
1193 public static unsafe void WriteInt16 (IntPtr ptr, short val)
1195 byte *addr = (byte *) ptr;
1197 if (((uint)addr & 1) == 0)
1198 *(short*)addr = val;
1200 String.memcpy (addr, (byte*)&val, 2);
1203 public static unsafe void WriteInt16 (IntPtr ptr, int ofs, short val)
1205 byte *addr = ((byte *) ptr) + ofs;
1207 if (((uint)addr & 1) == 0)
1208 *(short*)addr = val;
1210 String.memcpy (addr, (byte*)&val, 2);
1215 [SuppressUnmanagedCodeSecurity]
1216 public static void WriteInt16 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, short val)
1218 throw new NotImplementedException ();
1221 public static void WriteInt16 (IntPtr ptr, char val)
1223 WriteInt16 (ptr, 0, (short)val);
1226 public static void WriteInt16 (IntPtr ptr, int ofs, char val)
1228 WriteInt16 (ptr, ofs, (short)val);
1232 public static void WriteInt16([In, Out] object ptr, int ofs, char val)
1234 throw new NotImplementedException ();
1237 public static unsafe void WriteInt32 (IntPtr ptr, int val)
1239 byte *addr = (byte *) ptr;
1241 if (((uint)addr & 3) == 0)
1244 String.memcpy (addr, (byte*)&val, 4);
1248 public unsafe static void WriteInt32 (IntPtr ptr, int ofs, int val)
1250 byte *addr = ((byte *) ptr) + ofs;
1252 if (((uint)addr & 3) == 0)
1255 String.memcpy (addr, (byte*)&val, 4);
1260 [SuppressUnmanagedCodeSecurity]
1261 public static void WriteInt32([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, int val)
1263 throw new NotImplementedException ();
1266 public static unsafe void WriteInt64 (IntPtr ptr, long val)
1268 byte *addr = (byte *) ptr;
1270 // The real alignment might be 4 on some platforms, but this is just an optimization,
1271 // so it doesn't matter.
1272 if (((uint)addr & 7) == 0)
1275 String.memcpy (addr, (byte*)&val, 8);
1278 public static unsafe void WriteInt64 (IntPtr ptr, int ofs, long val)
1280 byte *addr = ((byte *) ptr) + ofs;
1282 // The real alignment might be 4 on some platforms, but this is just an optimization,
1283 // so it doesn't matter.
1284 if (((uint)addr & 7) == 0)
1287 String.memcpy (addr, (byte*)&val, 8);
1291 [SuppressUnmanagedCodeSecurity]
1292 public static void WriteInt64 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, long val)
1294 throw new NotImplementedException ();
1297 public static void WriteIntPtr (IntPtr ptr, IntPtr val)
1299 if (IntPtr.Size == 4)
1300 WriteInt32 (ptr, (int)val);
1302 WriteInt64 (ptr, (long)val);
1305 public static void WriteIntPtr (IntPtr ptr, int ofs, IntPtr val)
1307 if (IntPtr.Size == 4)
1308 WriteInt32 (ptr, ofs, (int)val);
1310 WriteInt64 (ptr, ofs, (long)val);
1314 public static void WriteIntPtr([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, IntPtr val)
1316 throw new NotImplementedException ();
1319 private static Exception ConvertHrToException (int errorCode)
1321 const int MSEE_E_APPDOMAINUNLOADED = unchecked ((int)0x80131014L);
1322 const int COR_E_APPLICATION = unchecked ((int)0x80131600L);
1323 const int E_INVALIDARG = unchecked ((int)0x80070057);
1324 const int COR_E_ARGUMENTOUTOFRANGE = unchecked ((int)0x80131502L);
1325 const int COR_E_ARITHMETIC = unchecked ((int)0x80070216);
1326 const int COR_E_ARRAYTYPEMISMATCH = unchecked ((int)0x80131503L);
1327 const int COR_E_BADIMAGEFORMAT = unchecked ((int)0x8007000BL);
1328 const int ERROR_BAD_FORMAT = unchecked ((int)0x0B);
1329 //const int COR_E_COMEMULATE_ERROR = unchecked ((int)?);
1330 const int COR_E_CONTEXTMARSHAL = unchecked ((int)0x80131504L);
1331 //const int COR_E_CORE = unchecked ((int)?);
1332 const int NTE_FAIL = unchecked ((int)0x80090020L);
1333 const int COR_E_DIRECTORYNOTFOUND = unchecked ((int)0x80070003L);
1334 const int ERROR_PATH_NOT_FOUND = unchecked ((int)0x03);
1335 const int COR_E_DIVIDEBYZERO = unchecked ((int)0x80020012L);
1336 const int COR_E_DUPLICATEWAITOBJECT = unchecked ((int)0x80131529L);
1337 const int COR_E_ENDOFSTREAM = unchecked ((int)0x80070026L);
1338 const int COR_E_TYPELOAD = unchecked ((int)0x80131522L);
1339 const int COR_E_EXCEPTION = unchecked ((int)0x80131500L);
1340 const int COR_E_EXECUTIONENGINE = unchecked ((int)0x80131506L);
1341 const int COR_E_FIELDACCESS = unchecked ((int)0x80131507L);
1342 const int COR_E_FILENOTFOUND = unchecked ((int)0x80070002L);
1343 const int ERROR_FILE_NOT_FOUND = unchecked ((int)0x02);
1344 const int COR_E_FORMAT = unchecked ((int)0x80131537L);
1345 const int COR_E_INDEXOUTOFRANGE = unchecked ((int)0x80131508L);
1346 const int COR_E_INVALIDCAST = unchecked ((int)0x80004002L);
1347 const int COR_E_INVALIDCOMOBJECT = unchecked ((int)0x80131527L);
1348 const int COR_E_INVALIDFILTERCRITERIA = unchecked ((int)0x80131601L);
1349 const int COR_E_INVALIDOLEVARIANTTYPE = unchecked ((int)0x80131531L);
1350 const int COR_E_INVALIDOPERATION = unchecked ((int)0x80131509L);
1351 const int COR_E_IO = unchecked ((int)0x80131620L);
1352 const int COR_E_MEMBERACCESS = unchecked ((int)0x8013151AL);
1353 const int COR_E_METHODACCESS = unchecked ((int)0x80131510L);
1354 const int COR_E_MISSINGFIELD = unchecked ((int)0x80131511L);
1355 const int COR_E_MISSINGMANIFESTRESOURCE = unchecked ((int)0x80131532L);
1356 const int COR_E_MISSINGMEMBER = unchecked ((int)0x80131512L);
1357 const int COR_E_MISSINGMETHOD = unchecked ((int)0x80131513L);
1358 const int COR_E_MULTICASTNOTSUPPORTED = unchecked ((int)0x80131514L);
1359 const int COR_E_NOTFINITENUMBER = unchecked ((int)0x80131528L);
1360 const int E_NOTIMPL = unchecked ((int)0x80004001L);
1361 const int COR_E_NOTSUPPORTED = unchecked ((int)0x80131515L);
1362 const int COR_E_NULLREFERENCE = unchecked ((int)0x80004003L);
1363 const int E_OUTOFMEMORY = unchecked ((int)0x8007000EL);
1364 const int COR_E_OVERFLOW = unchecked ((int)0x80131516L);
1365 const int COR_E_PATHTOOLONG = unchecked ((int)0x800700CEL);
1366 const int ERROR_FILENAME_EXCED_RANGE = unchecked ((int)0xCE);
1367 const int COR_E_RANK = unchecked ((int)0x80131517L);
1368 const int COR_E_REFLECTIONTYPELOAD = unchecked ((int)0x80131602L);
1369 const int COR_E_REMOTING = unchecked ((int)0x8013150BL);
1370 const int COR_E_SAFEARRAYTYPEMISMATCH = unchecked ((int)0x80131533L);
1371 const int COR_E_SECURITY = unchecked ((int)0x8013150AL);
1372 const int COR_E_SERIALIZATION = unchecked ((int)0x8013150CL);
1373 const int COR_E_STACKOVERFLOW = unchecked ((int)0x800703E9L);
1374 const int ERROR_STACK_OVERFLOW = unchecked ((int)0x03E9);
1375 const int COR_E_SYNCHRONIZATIONLOCK = unchecked ((int)0x80131518L);
1376 const int COR_E_SYSTEM = unchecked ((int)0x80131501L);
1377 const int COR_E_TARGET = unchecked ((int)0x80131603L);
1378 const int COR_E_TARGETINVOCATION = unchecked ((int)0x80131604L);
1379 const int COR_E_TARGETPARAMCOUNT = unchecked ((int)0x8002000EL);
1380 const int COR_E_THREADABORTED = unchecked ((int)0x80131530L);
1381 const int COR_E_THREADINTERRUPTED = unchecked ((int)0x80131519L);
1382 const int COR_E_THREADSTATE = unchecked ((int)0x80131520L);
1383 const int COR_E_THREADSTOP = unchecked ((int)0x80131521L);
1384 const int COR_E_TYPEINITIALIZATION = unchecked ((int)0x80131534L);
1385 const int COR_E_VERIFICATION = unchecked ((int)0x8013150DL);
1386 //const int COR_E_WEAKREFERENCE = unchecked ((int)?);
1387 //const int COR_E_VTABLECALLSNOTSUPPORTED = unchecked ((int));
1389 switch (errorCode) {
1390 case MSEE_E_APPDOMAINUNLOADED:
1391 return new AppDomainUnloadedException ();
1392 case COR_E_APPLICATION:
1393 return new ApplicationException ();
1395 return new ArgumentException ();
1396 case COR_E_ARGUMENTOUTOFRANGE:
1397 return new ArgumentOutOfRangeException ();
1398 case COR_E_ARITHMETIC:
1399 return new ArithmeticException ();
1400 case COR_E_ARRAYTYPEMISMATCH:
1401 return new ArrayTypeMismatchException ();
1402 case COR_E_BADIMAGEFORMAT:
1403 case ERROR_BAD_FORMAT:
1404 return new BadImageFormatException ();
1405 // case COR_E_COMEMULATE_ERROR:
1406 // return new COMEmulateException ();
1407 case COR_E_CONTEXTMARSHAL:
1408 return new ContextMarshalException ();
1410 // return new CoreException ();
1412 return new System.Security.Cryptography.CryptographicException ();
1413 case COR_E_DIRECTORYNOTFOUND:
1414 case ERROR_PATH_NOT_FOUND:
1415 return new System.IO.DirectoryNotFoundException ();
1416 case COR_E_DIVIDEBYZERO:
1417 return new DivideByZeroException ();
1418 case COR_E_DUPLICATEWAITOBJECT:
1419 return new DuplicateWaitObjectException ();
1420 case COR_E_ENDOFSTREAM:
1421 return new System.IO.EndOfStreamException ();
1422 case COR_E_EXCEPTION:
1423 return new Exception ();
1424 case COR_E_EXECUTIONENGINE:
1425 return new ExecutionEngineException ();
1426 case COR_E_FIELDACCESS:
1427 return new FieldAccessException ();
1428 case COR_E_FILENOTFOUND:
1429 case ERROR_FILE_NOT_FOUND:
1430 return new System.IO.FileNotFoundException ();
1432 return new FormatException ();
1433 case COR_E_INDEXOUTOFRANGE:
1434 return new IndexOutOfRangeException ();
1435 case COR_E_INVALIDCAST:
1436 // E_NOINTERFACE has same value as COR_E_INVALIDCAST
1437 return new InvalidCastException ();
1438 case COR_E_INVALIDCOMOBJECT:
1439 return new InvalidComObjectException ();
1440 case COR_E_INVALIDFILTERCRITERIA:
1441 return new InvalidFilterCriteriaException ();
1442 case COR_E_INVALIDOLEVARIANTTYPE:
1443 return new InvalidOleVariantTypeException ();
1444 case COR_E_INVALIDOPERATION:
1445 return new InvalidOperationException ();
1447 return new System.IO.IOException ();
1448 case COR_E_MEMBERACCESS:
1449 return new MemberAccessException ();
1450 case COR_E_METHODACCESS:
1451 return new MethodAccessException ();
1452 case COR_E_MISSINGFIELD:
1453 return new MissingFieldException ();
1454 case COR_E_MISSINGMANIFESTRESOURCE:
1455 return new System.Resources.MissingManifestResourceException ();
1456 case COR_E_MISSINGMEMBER:
1457 return new MissingMemberException ();
1458 case COR_E_MISSINGMETHOD:
1459 return new MissingMethodException ();
1460 case COR_E_MULTICASTNOTSUPPORTED:
1461 return new MulticastNotSupportedException ();
1462 case COR_E_NOTFINITENUMBER:
1463 return new NotFiniteNumberException ();
1465 return new NotImplementedException ();
1466 case COR_E_NOTSUPPORTED:
1467 return new NotSupportedException ();
1468 case COR_E_NULLREFERENCE:
1469 // E_POINTER has the same value as COR_E_NULLREFERENCE
1470 return new NullReferenceException ();
1472 // COR_E_OUTOFMEMORY has the same value as E_OUTOFMEMORY
1473 return new OutOfMemoryException ();
1474 case COR_E_OVERFLOW:
1475 return new OverflowException ();
1476 case COR_E_PATHTOOLONG:
1477 case ERROR_FILENAME_EXCED_RANGE:
1478 return new System.IO.PathTooLongException ();
1480 return new RankException ();
1481 case COR_E_REFLECTIONTYPELOAD:
1482 return new System.Reflection.ReflectionTypeLoadException (new Type[] { }, new Exception[] { });
1483 case COR_E_REMOTING:
1484 return new System.Runtime.Remoting.RemotingException ();
1485 case COR_E_SAFEARRAYTYPEMISMATCH:
1486 return new SafeArrayTypeMismatchException ();
1487 case COR_E_SECURITY:
1488 return new SecurityException ();
1489 case COR_E_SERIALIZATION:
1490 return new System.Runtime.Serialization.SerializationException ();
1491 case COR_E_STACKOVERFLOW:
1492 case ERROR_STACK_OVERFLOW:
1493 return new StackOverflowException ();
1494 case COR_E_SYNCHRONIZATIONLOCK:
1495 return new SynchronizationLockException ();
1497 return new SystemException ();
1499 return new TargetException ();
1500 case COR_E_TARGETINVOCATION:
1501 return new System.Reflection.TargetInvocationException (null);
1502 case COR_E_TARGETPARAMCOUNT:
1503 return new TargetParameterCountException ();
1504 // case COR_E_THREADABORTED:
1505 // ThreadAbortException c'tor is inaccessible
1506 // return new System.Threading.ThreadAbortException ();
1507 case COR_E_THREADINTERRUPTED:
1508 return new ThreadInterruptedException ();
1509 case COR_E_THREADSTATE:
1510 return new ThreadStateException ();
1511 // case COR_E_THREADSTOP:
1512 // ThreadStopException does not exist
1513 // return new System.Threading.ThreadStopException ();
1514 case COR_E_TYPELOAD:
1515 return new TypeLoadException ();
1516 // MSDN lists COR_E_TYPELOAD twice with different exceptions.
1517 // return new EntryPointNotFoundException ();
1518 case COR_E_TYPEINITIALIZATION:
1519 return new TypeInitializationException("", null);
1520 case COR_E_VERIFICATION:
1521 return new VerificationException ();
1522 // case COR_E_WEAKREFERENCE:
1523 // return new WeakReferenceException ();
1524 // case COR_E_VTABLECALLSNOTSUPPORTED:
1525 // return new VTableCallsNotSupportedException ();
1528 return new COMException ("", errorCode);
1532 [DllImport ("oleaut32.dll", CharSet=CharSet.Unicode, EntryPoint = "SetErrorInfo")]
1533 static extern int _SetErrorInfo (int dwReserved,
1534 [MarshalAs(UnmanagedType.Interface)] IErrorInfo pIErrorInfo);
1536 [DllImport ("oleaut32.dll", CharSet=CharSet.Unicode, EntryPoint = "GetErrorInfo")]
1537 static extern int _GetErrorInfo (int dwReserved,
1538 [MarshalAs(UnmanagedType.Interface)] out IErrorInfo ppIErrorInfo);
1540 static bool SetErrorInfoNotAvailable;
1541 static bool GetErrorInfoNotAvailable;
1543 internal static int SetErrorInfo (int dwReserved, IErrorInfo errorInfo)
1548 if (SetErrorInfoNotAvailable)
1552 retVal = _SetErrorInfo (dwReserved, errorInfo);
1555 // ignore any exception - probably there's no suitable SetErrorInfo
1556 // method available.
1557 SetErrorInfoNotAvailable = true;
1562 internal static int GetErrorInfo (int dwReserved, out IErrorInfo errorInfo)
1567 if (GetErrorInfoNotAvailable)
1571 retVal = _GetErrorInfo (dwReserved, out errorInfo);
1574 // ignore any exception - probably there's no suitable GetErrorInfo
1575 // method available.
1576 GetErrorInfoNotAvailable = true;
1581 public static Exception GetExceptionForHR (int errorCode)
1583 return GetExceptionForHR (errorCode, IntPtr.Zero);
1586 public static Exception GetExceptionForHR (int errorCode, IntPtr errorInfo)
1589 IErrorInfo info = null;
1590 if (errorInfo != (IntPtr)(-1)) {
1591 if (errorInfo == IntPtr.Zero) {
1592 if (GetErrorInfo (0, out info) != 0) {
1596 info = Marshal.GetObjectForIUnknown (errorInfo) as IErrorInfo;
1600 if (info is ManagedErrorInfo && ((ManagedErrorInfo) info).Exception.hresult == errorCode) {
1601 return ((ManagedErrorInfo) info).Exception;
1604 Exception e = ConvertHrToException (errorCode);
1605 if (info != null && e != null) {
1607 info.GetHelpContext (out helpContext);
1609 info.GetSource (out str);
1611 info.GetDescription (out str);
1613 info.GetHelpFile (out str);
1615 if (helpContext == 0) {
1618 e.HelpLink = string.Format ("{0}#{1}", str, helpContext);
1623 return ConvertHrToException (errorCode);
1627 #if !FULL_AOT_RUNTIME
1628 public static int FinalReleaseComObject (object o)
1630 while (ReleaseComObject (o) != 0);
1635 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1636 private static extern Delegate GetDelegateForFunctionPointerInternal (IntPtr ptr, Type t);
1638 public static Delegate GetDelegateForFunctionPointer (IntPtr ptr, Type t)
1641 throw new ArgumentNullException ("t");
1642 if (!t.IsSubclassOf (typeof (MulticastDelegate)) || (t == typeof (MulticastDelegate)))
1643 throw new ArgumentException ("Type is not a delegate", "t");
1644 if (t.IsGenericType)
1645 throw new ArgumentException ("The specified Type must not be a generic type definition.");
1646 if (ptr == IntPtr.Zero)
1647 throw new ArgumentNullException ("ptr");
1649 return GetDelegateForFunctionPointerInternal (ptr, t);
1653 public static TDelegate GetDelegateForFunctionPointer<TDelegate> (IntPtr ptr) {
1654 return (TDelegate) (object) GetDelegateForFunctionPointer (ptr, typeof (TDelegate));
1658 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1659 private static extern IntPtr GetFunctionPointerForDelegateInternal (Delegate d);
1661 public static IntPtr GetFunctionPointerForDelegate (Delegate d)
1664 throw new ArgumentNullException ("d");
1666 return GetFunctionPointerForDelegateInternal (d);
1670 public static IntPtr GetFunctionPointerForDelegate<TDelegate> (TDelegate d) {
1672 throw new ArgumentNullException ("d");
1674 return GetFunctionPointerForDelegateInternal ((Delegate)(object)d);