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 ();
190 public static IntPtr CreateAggregatedObject<T> (IntPtr pOuter, T o) {
191 return CreateAggregatedObject (pOuter, (object)o);
194 #if !FULL_AOT_RUNTIME
195 public static object CreateWrapperOfType (object o, Type t)
197 __ComObject co = o as __ComObject;
199 throw new ArgumentException ("o must derive from __ComObject", "o");
201 throw new ArgumentNullException ("t");
203 Type[] itfs = o.GetType ().GetInterfaces ();
204 foreach (Type itf in itfs) {
205 if (itf.IsImport && co.GetInterface (itf) == IntPtr.Zero)
206 throw new InvalidCastException ();
209 return ComInteropProxy.GetProxy (co.IUnknown, t).GetTransparentProxy ();
212 public static TWrapper CreateWrapperOfType<T, TWrapper> (T o) {
213 return (TWrapper)CreateWrapperOfType ((object)o, typeof (TWrapper));
217 [MethodImplAttribute(MethodImplOptions.InternalCall)]
219 public extern static void DestroyStructure (IntPtr ptr, Type structuretype);
221 public static void DestroyStructure<T> (IntPtr ptr) {
222 DestroyStructure (ptr, typeof (T));
225 [MethodImplAttribute(MethodImplOptions.InternalCall)]
226 public extern static void FreeBSTR (IntPtr ptr);
228 [MethodImplAttribute(MethodImplOptions.InternalCall)]
229 public extern static void FreeCoTaskMem (IntPtr ptr);
231 [MethodImplAttribute(MethodImplOptions.InternalCall)]
232 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
233 public extern static void FreeHGlobal (IntPtr hglobal);
235 static void ClearBSTR (IntPtr ptr)
237 int len = ReadInt32 (ptr, -4);
239 for (int i = 0; i < len; i++)
240 WriteByte (ptr, i, 0);
243 public static void ZeroFreeBSTR (IntPtr s)
249 static void ClearAnsi (IntPtr ptr)
251 for (int i = 0; ReadByte (ptr, i) != 0; i++)
252 WriteByte (ptr, i, 0);
255 static void ClearUnicode (IntPtr ptr)
257 for (int i = 0; ReadInt16 (ptr, i) != 0; i += 2)
258 WriteInt16 (ptr, i, 0);
261 public static void ZeroFreeCoTaskMemAnsi (IntPtr s)
267 public static void ZeroFreeCoTaskMemUnicode (IntPtr s)
273 public static void ZeroFreeGlobalAllocAnsi (IntPtr s)
279 public static void ZeroFreeGlobalAllocUnicode (IntPtr s)
285 #if !FULL_AOT_RUNTIME
286 public static Guid GenerateGuidForType (Type type)
291 public static string GenerateProgIdForType (Type type)
293 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (type);
295 foreach (var a in attrs)
297 var dt = a.Constructor.DeclaringType;
298 string name = dt.Name;
299 if (name == "ProgIdAttribute")
301 var args = a.ConstructorArguments;
302 string text = a.ConstructorArguments[0].Value as string;
311 return type.FullName;
315 public static object GetActiveObject (string progID)
317 throw new NotImplementedException ();
321 [MethodImplAttribute (MethodImplOptions.InternalCall)]
322 private extern static IntPtr GetCCW (object o, Type T);
324 private static IntPtr GetComInterfaceForObjectInternal (object o, Type T)
327 return ((__ComObject)o).GetInterface (T);
329 return GetCCW (o, T);
333 public static IntPtr GetComInterfaceForObject (object o, Type T)
336 IntPtr pItf = GetComInterfaceForObjectInternal (o, T);
340 throw new NotImplementedException ();
344 public static IntPtr GetComInterfaceForObject<T, TInterface> (T o) {
345 return GetComInterfaceForObject ((object)o, typeof (T));
349 public static IntPtr GetComInterfaceForObjectInContext (object o, Type t)
351 throw new NotImplementedException ();
354 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
355 public static object GetComObjectData (object obj, object key)
357 throw new NotSupportedException ("MSDN states user code should never need to call this method.");
361 [MethodImplAttribute(MethodImplOptions.InternalCall)]
362 private extern static int GetComSlotForMethodInfoInternal (MemberInfo m);
365 public static int GetComSlotForMethodInfo (MemberInfo m)
369 throw new ArgumentNullException ("m");
370 if (!(m is MethodInfo))
371 throw new ArgumentException ("The MemberInfo must be an interface method.", "m");
372 if (!m.DeclaringType.IsInterface)
373 throw new ArgumentException ("The MemberInfo must be an interface method.", "m");
374 return GetComSlotForMethodInfoInternal (m);
376 throw new NotImplementedException ();
381 public static int GetEndComSlot (Type t)
383 throw new NotImplementedException ();
387 public static int GetExceptionCode()
389 throw new NotImplementedException ();
394 public static IntPtr GetExceptionPointers()
396 throw new NotImplementedException ();
399 public static IntPtr GetHINSTANCE (Module m)
402 throw new ArgumentNullException ("m");
404 return m.GetHINSTANCE ();
406 #endif // !FULL_AOT_RUNTIME
408 #if !FULL_AOT_RUNTIME
409 public static int GetHRForException (Exception e)
411 var errorInfo = new ManagedErrorInfo(e);
412 SetErrorInfo (0, errorInfo);
418 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
419 public static int GetHRForLastWin32Error()
421 throw new NotImplementedException ();
424 [MethodImplAttribute (MethodImplOptions.InternalCall)]
425 private extern static IntPtr GetIDispatchForObjectInternal (object o);
427 public static IntPtr GetIDispatchForObject (object o)
429 IntPtr pUnk = GetIDispatchForObjectInternal (o);
430 // Internal method does not AddRef
436 public static IntPtr GetIDispatchForObjectInContext (object o)
438 throw new NotImplementedException ();
442 public static IntPtr GetITypeInfoForType (Type t)
444 throw new NotImplementedException ();
447 [MethodImplAttribute (MethodImplOptions.InternalCall)]
448 private extern static IntPtr GetIUnknownForObjectInternal (object o);
450 public static IntPtr GetIUnknownForObject (object o)
452 IntPtr pUnk = GetIUnknownForObjectInternal (o);
453 // Internal method does not AddRef
459 public static IntPtr GetIUnknownForObjectInContext (object o)
461 throw new NotImplementedException ();
465 [Obsolete ("This method has been deprecated")]
466 public static IntPtr GetManagedThunkForUnmanagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
468 throw new NotImplementedException ();
472 public static MemberInfo GetMethodInfoForComSlot (Type t, int slot, ref ComMemberType memberType)
474 throw new NotImplementedException ();
477 public static void GetNativeVariantForObject (object obj, IntPtr pDstNativeVariant)
479 Variant vt = new Variant();
481 Marshal.StructureToPtr(vt, pDstNativeVariant, false);
484 public static void GetNativeVariantForObject<T> (T obj, IntPtr pDstNativeVariant) {
485 GetNativeVariantForObject ((object)obj, pDstNativeVariant);
489 [MethodImplAttribute (MethodImplOptions.InternalCall)]
490 private static extern object GetObjectForCCW (IntPtr pUnk);
493 public static object GetObjectForIUnknown (IntPtr pUnk)
496 object obj = GetObjectForCCW (pUnk);
499 ComInteropProxy proxy = ComInteropProxy.GetProxy (pUnk, typeof (__ComObject));
500 obj = proxy.GetTransparentProxy ();
504 throw new NotImplementedException ();
508 public static object GetObjectForNativeVariant (IntPtr pSrcNativeVariant)
510 Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
511 return vt.GetValue();
514 public static T GetObjectForNativeVariant<T> (IntPtr pSrcNativeVariant) {
515 Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
516 return (T)vt.GetValue();
519 public static object[] GetObjectsForNativeVariants (IntPtr aSrcNativeVariant, int cVars)
522 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
523 object[] objects = new object[cVars];
524 for (int i = 0; i < cVars; i++)
525 objects[i] = GetObjectForNativeVariant ((IntPtr)(aSrcNativeVariant.ToInt64 () +
526 i * SizeOf (typeof(Variant))));
530 public static T[] GetObjectsForNativeVariants<T> (IntPtr aSrcNativeVariant, int cVars) {
532 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
533 T[] objects = new T[cVars];
534 for (int i = 0; i < cVars; i++)
535 objects[i] = GetObjectForNativeVariant<T> ((IntPtr)(aSrcNativeVariant.ToInt64 () +
536 i * SizeOf (typeof(Variant))));
541 public static int GetStartComSlot (Type t)
543 throw new NotImplementedException ();
547 [Obsolete ("This method has been deprecated")]
548 public static Thread GetThreadFromFiberCookie (int cookie)
550 throw new NotImplementedException ();
553 public static object GetTypedObjectForIUnknown (IntPtr pUnk, Type t)
555 ComInteropProxy proxy = new ComInteropProxy (pUnk, t);
556 __ComObject co = (__ComObject)proxy.GetTransparentProxy ();
557 foreach (Type itf in t.GetInterfaces ()) {
558 if ((itf.Attributes & TypeAttributes.Import) == TypeAttributes.Import) {
559 if (co.GetInterface (itf) == IntPtr.Zero)
567 public static Type GetTypeForITypeInfo (IntPtr piTypeInfo)
569 throw new NotImplementedException ();
572 public static Type GetTypeFromCLSID (Guid clsid)
574 throw new NotImplementedException ();
577 #if !FULL_AOT_RUNTIME
580 public static string GetTypeInfoName (UCOMITypeInfo pTI)
582 throw new NotImplementedException ();
585 public static string GetTypeInfoName (ITypeInfo typeInfo)
587 throw new NotImplementedException ();
592 public static Guid GetTypeLibGuid (UCOMITypeLib pTLB)
594 throw new NotImplementedException ();
598 public static Guid GetTypeLibGuid (ITypeLib typelib)
600 throw new NotImplementedException ();
604 public static Guid GetTypeLibGuidForAssembly (Assembly asm)
606 throw new NotImplementedException ();
611 public static int GetTypeLibLcid (UCOMITypeLib pTLB)
613 throw new NotImplementedException ();
617 public static int GetTypeLibLcid (ITypeLib typelib)
619 throw new NotImplementedException ();
624 public static string GetTypeLibName (UCOMITypeLib pTLB)
626 throw new NotImplementedException ();
630 public static string GetTypeLibName (ITypeLib typelib)
632 throw new NotImplementedException ();
636 public static void GetTypeLibVersionForAssembly (Assembly inputAssembly, out int majorVersion, out int minorVersion)
638 throw new NotImplementedException ();
641 public static object GetUniqueObjectForIUnknown (IntPtr unknown)
643 throw new NotImplementedException ();
648 [Obsolete ("This method has been deprecated")]
649 public static IntPtr GetUnmanagedThunkForManagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
651 throw new NotImplementedException ();
655 [MethodImplAttribute (MethodImplOptions.InternalCall)]
656 public extern static bool IsComObject (object o);
658 public static bool IsComObject (object o)
660 throw new NotImplementedException ();
665 public static bool IsTypeVisibleFromCom (Type t)
667 throw new NotImplementedException ();
671 public static int NumParamBytes (MethodInfo m)
673 throw new NotImplementedException ();
677 [MethodImplAttribute(MethodImplOptions.InternalCall)]
678 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
679 public static extern int GetLastWin32Error();
681 [MethodImplAttribute(MethodImplOptions.InternalCall)]
682 public extern static IntPtr OffsetOf (Type t, string fieldName);
684 public static IntPtr OffsetOf<T> (string fieldName) {
685 return OffsetOf (typeof (T), fieldName);
688 [MethodImplAttribute(MethodImplOptions.InternalCall)]
689 public extern static void Prelink (MethodInfo m);
691 [MethodImplAttribute(MethodImplOptions.InternalCall)]
692 public extern static void PrelinkAll (Type c);
694 [MethodImplAttribute(MethodImplOptions.InternalCall)]
695 public extern static string PtrToStringAnsi (IntPtr ptr);
697 [MethodImplAttribute(MethodImplOptions.InternalCall)]
698 public extern static string PtrToStringAnsi (IntPtr ptr, int len);
700 public static string PtrToStringAuto (IntPtr ptr)
702 return SystemDefaultCharSize == 2
703 ? PtrToStringUni (ptr) : PtrToStringAnsi (ptr);
706 public static string PtrToStringAuto (IntPtr ptr, int len)
708 return SystemDefaultCharSize == 2
709 ? PtrToStringUni (ptr, len) : PtrToStringAnsi (ptr, len);
712 [MethodImplAttribute(MethodImplOptions.InternalCall)]
713 public extern static string PtrToStringUni (IntPtr ptr);
715 [MethodImplAttribute(MethodImplOptions.InternalCall)]
716 public extern static string PtrToStringUni (IntPtr ptr, int len);
719 [MethodImplAttribute(MethodImplOptions.InternalCall)]
720 public extern static string PtrToStringBSTR (IntPtr ptr);
722 public static string PtrToStringBSTR (IntPtr ptr)
724 throw new NotImplementedException ();
728 [MethodImplAttribute(MethodImplOptions.InternalCall)]
730 public extern static void PtrToStructure (IntPtr ptr, object structure);
732 [MethodImplAttribute(MethodImplOptions.InternalCall)]
734 public extern static object PtrToStructure (IntPtr ptr, Type structureType);
736 public static void PtrToStructure<T> (IntPtr ptr, T structure) {
737 PtrToStructure (ptr, (object)structure);
740 public static T PtrToStructure<T> (IntPtr ptr) {
741 return (T) PtrToStructure (ptr, typeof (T));
745 [MethodImplAttribute (MethodImplOptions.InternalCall)]
746 private extern static int QueryInterfaceInternal (IntPtr pUnk, ref Guid iid, out IntPtr ppv);
749 public static int QueryInterface (IntPtr pUnk, ref Guid iid, out IntPtr ppv)
752 if (pUnk == IntPtr.Zero)
753 throw new ArgumentException ("Value cannot be null.", "pUnk");
754 return QueryInterfaceInternal (pUnk, ref iid, out ppv);
756 throw new NotImplementedException ();
760 public static byte ReadByte (IntPtr ptr)
767 public static byte ReadByte (IntPtr ptr, int ofs) {
769 return *((byte*)ptr + ofs);
774 [SuppressUnmanagedCodeSecurity]
775 public static byte ReadByte ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
777 throw new NotImplementedException ();
780 public unsafe static short ReadInt16 (IntPtr ptr)
782 byte *addr = (byte *) ptr;
784 // The mono JIT can't inline this due to the hight number of calls
785 // return ReadInt16 (ptr, 0);
787 if (((uint)addr & 1) == 0)
788 return *(short*)addr;
791 String.memcpy ((byte*)&s, (byte*)ptr, 2);
795 public unsafe static short ReadInt16 (IntPtr ptr, int ofs)
797 byte *addr = ((byte *) ptr) + ofs;
799 if (((uint) addr & 1) == 0)
800 return *(short*)addr;
803 String.memcpy ((byte*)&s, addr, 2);
808 [SuppressUnmanagedCodeSecurity]
809 public static short ReadInt16 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
811 throw new NotImplementedException ();
814 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
815 public unsafe static int ReadInt32 (IntPtr ptr)
817 byte *addr = (byte *) ptr;
819 if (((uint)addr & 3) == 0)
823 String.memcpy ((byte*)&s, addr, 4);
827 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
828 public unsafe static int ReadInt32 (IntPtr ptr, int ofs)
830 byte *addr = ((byte *) ptr) + ofs;
832 if ((((int) addr) & 3) == 0)
836 String.memcpy ((byte*)&s, addr, 4);
841 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
843 [SuppressUnmanagedCodeSecurity]
844 public static int ReadInt32 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
846 throw new NotImplementedException ();
849 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
850 public unsafe static long ReadInt64 (IntPtr ptr)
852 byte *addr = (byte *) ptr;
854 // The real alignment might be 4 on some platforms, but this is just an optimization,
855 // so it doesn't matter.
856 if (((uint) addr & 7) == 0)
860 String.memcpy ((byte*)&s, addr, 8);
864 public unsafe static long ReadInt64 (IntPtr ptr, int ofs)
866 byte *addr = ((byte *) ptr) + ofs;
868 if (((uint) addr & 7) == 0)
872 String.memcpy ((byte*)&s, addr, 8);
876 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
878 [SuppressUnmanagedCodeSecurity]
879 public static long ReadInt64 ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
881 throw new NotImplementedException ();
884 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
885 public static IntPtr ReadIntPtr (IntPtr ptr)
887 if (IntPtr.Size == 4)
888 return (IntPtr)ReadInt32 (ptr);
890 return (IntPtr)ReadInt64 (ptr);
893 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
894 public static IntPtr ReadIntPtr (IntPtr ptr, int ofs)
896 if (IntPtr.Size == 4)
897 return (IntPtr)ReadInt32 (ptr, ofs);
899 return (IntPtr)ReadInt64 (ptr, ofs);
902 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
904 public static IntPtr ReadIntPtr ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
906 throw new NotImplementedException ();
909 [MethodImplAttribute (MethodImplOptions.InternalCall)]
910 public extern static IntPtr ReAllocCoTaskMem (IntPtr pv, int cb);
912 [MethodImplAttribute(MethodImplOptions.InternalCall)]
913 public extern static IntPtr ReAllocHGlobal (IntPtr pv, IntPtr cb);
916 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
917 [MethodImplAttribute (MethodImplOptions.InternalCall)]
918 private extern static int ReleaseInternal (IntPtr pUnk);
921 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
922 public static int Release (IntPtr pUnk)
925 if (pUnk == IntPtr.Zero)
926 throw new ArgumentException ("Value cannot be null.", "pUnk");
928 return ReleaseInternal (pUnk);
930 throw new NotImplementedException ();
934 #if !FULL_AOT_RUNTIME
935 [MethodImplAttribute (MethodImplOptions.InternalCall)]
936 private extern static int ReleaseComObjectInternal (object co);
938 public static int ReleaseComObject (object o)
941 throw new ArgumentException ("Value cannot be null.", "o");
942 if (!IsComObject (o))
943 throw new ArgumentException ("Value must be a Com object.", "o");
944 return ReleaseComObjectInternal (o);
949 public static void ReleaseThreadCache()
951 throw new NotImplementedException ();
954 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
955 public static bool SetComObjectData (object obj, object key, object data)
957 throw new NotSupportedException ("MSDN states user code should never need to call this method.");
962 public static int SizeOf (object structure)
964 return SizeOf (structure.GetType ());
967 [MethodImplAttribute(MethodImplOptions.InternalCall)]
968 public extern static int SizeOf (Type t);
970 public static int SizeOf<T> () {
971 return SizeOf (typeof (T));
974 public static int SizeOf<T> (T structure) {
975 return SizeOf (structure.GetType ());
978 [MethodImplAttribute(MethodImplOptions.InternalCall)]
979 public extern static IntPtr StringToBSTR (string s);
982 // I believe this is wrong, because in Mono and in P/Invoke
983 // we treat "Ansi" conversions as UTF-8 conversions, while
984 // this one does not do this
986 public static IntPtr StringToCoTaskMemAnsi (string s)
988 int length = s.Length + 1;
989 IntPtr ctm = AllocCoTaskMem (length);
991 byte[] asBytes = new byte[length];
992 for (int i = 0; i < s.Length; i++)
993 asBytes[i] = (byte)s[i];
994 asBytes[s.Length] = 0;
996 copy_to_unmanaged (asBytes, 0, ctm, length);
1000 public static IntPtr StringToCoTaskMemAuto (string s)
1002 return SystemDefaultCharSize == 2
1003 ? StringToCoTaskMemUni (s) : StringToCoTaskMemAnsi (s);
1006 public static IntPtr StringToCoTaskMemUni (string s)
1008 int length = s.Length + 1;
1009 IntPtr ctm = AllocCoTaskMem (length * 2);
1011 char[] asChars = new char[length];
1012 s.CopyTo (0, asChars, 0, s.Length);
1013 asChars[s.Length] = '\0';
1015 copy_to_unmanaged (asChars, 0, ctm, length);
1019 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1020 public extern static IntPtr StringToHGlobalAnsi (string s);
1022 public static IntPtr StringToHGlobalAuto (string s)
1024 return SystemDefaultCharSize == 2
1025 ? StringToHGlobalUni (s) : StringToHGlobalAnsi (s);
1028 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1029 public extern static IntPtr StringToHGlobalUni (string s);
1031 public static IntPtr SecureStringToBSTR (SecureString s)
1034 throw new ArgumentNullException ("s");
1036 IntPtr ctm = AllocCoTaskMem ((len+1) * 2 + 4);
1037 byte [] buffer = null;
1038 WriteInt32 (ctm, 0, len*2);
1040 buffer = s.GetBuffer ();
1042 for (int i = 0; i < len; i++)
1043 WriteInt16 (ctm, 4 + (i * 2), (short) ((buffer [(i*2)] << 8) | (buffer [i*2+1])));
1044 WriteInt16 (ctm, 4 + buffer.Length, 0);
1047 for (int i = buffer.Length; i > 0; ){
1052 return (IntPtr) ((long)ctm + 4);
1055 public static IntPtr SecureStringToCoTaskMemAnsi (SecureString s)
1058 throw new ArgumentNullException ("s");
1060 IntPtr ctm = AllocCoTaskMem (len + 1);
1061 byte [] copy = new byte [len+1];
1064 byte [] buffer = s.GetBuffer ();
1066 for (; i < len; i++, j += 2){
1067 copy [i] = buffer [j+1];
1072 copy_to_unmanaged (copy, 0, ctm, len+1);
1074 // Ensure that we clear the buffer.
1075 for (int i = len; i > 0; ){
1083 public static IntPtr SecureStringToCoTaskMemUnicode (SecureString s)
1086 throw new ArgumentNullException ("s");
1088 IntPtr ctm = AllocCoTaskMem (len * 2 + 2);
1089 byte [] buffer = null;
1091 buffer = s.GetBuffer ();
1092 for (int i = 0; i < len; i++)
1093 WriteInt16 (ctm, i * 2, (short) ((buffer [(i*2)] << 8) | (buffer [i*2+1])));
1094 WriteInt16 (ctm, buffer.Length, 0);
1097 for (int i = buffer.Length; i > 0; ){
1105 public static IntPtr SecureStringToGlobalAllocAnsi (SecureString s)
1108 throw new ArgumentNullException ("s");
1109 return SecureStringToCoTaskMemAnsi (s);
1112 public static IntPtr SecureStringToGlobalAllocUnicode (SecureString s)
1115 throw new ArgumentNullException ("s");
1116 return SecureStringToCoTaskMemUnicode (s);
1119 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
1121 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1122 public extern static void StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld);
1124 public static void StructureToPtr<T> (T structure, IntPtr ptr, bool fDeleteOld) {
1125 StructureToPtr ((object)structure, ptr, fDeleteOld);
1128 public static void ThrowExceptionForHR (int errorCode) {
1129 Exception ex = GetExceptionForHR (errorCode);
1134 public static void ThrowExceptionForHR (int errorCode, IntPtr errorInfo) {
1135 Exception ex = GetExceptionForHR (errorCode, errorInfo);
1140 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1141 public extern static IntPtr UnsafeAddrOfPinnedArrayElement (Array arr, int index);
1143 public static IntPtr UnsafeAddrOfPinnedArrayElement<T> (T[] arr, int index) {
1144 return UnsafeAddrOfPinnedArrayElement ((Array)arr, index);
1147 public static void WriteByte (IntPtr ptr, byte val)
1154 public static void WriteByte (IntPtr ptr, int ofs, byte val) {
1156 *(byte*)(IntPtr.Add (ptr, ofs)) = val;
1161 [SuppressUnmanagedCodeSecurity]
1162 public static void WriteByte ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, byte val)
1164 throw new NotImplementedException ();
1167 public static unsafe void WriteInt16 (IntPtr ptr, short val)
1169 byte *addr = (byte *) ptr;
1171 if (((uint)addr & 1) == 0)
1172 *(short*)addr = val;
1174 String.memcpy (addr, (byte*)&val, 2);
1177 public static unsafe void WriteInt16 (IntPtr ptr, int ofs, short val)
1179 byte *addr = ((byte *) ptr) + ofs;
1181 if (((uint)addr & 1) == 0)
1182 *(short*)addr = val;
1184 String.memcpy (addr, (byte*)&val, 2);
1189 [SuppressUnmanagedCodeSecurity]
1190 public static void WriteInt16 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, short val)
1192 throw new NotImplementedException ();
1195 public static void WriteInt16 (IntPtr ptr, char val)
1197 WriteInt16 (ptr, 0, (short)val);
1200 public static void WriteInt16 (IntPtr ptr, int ofs, char val)
1202 WriteInt16 (ptr, ofs, (short)val);
1206 public static void WriteInt16([In, Out] object ptr, int ofs, char val)
1208 throw new NotImplementedException ();
1211 public static unsafe void WriteInt32 (IntPtr ptr, int val)
1213 byte *addr = (byte *) ptr;
1215 if (((uint)addr & 3) == 0)
1218 String.memcpy (addr, (byte*)&val, 4);
1222 public unsafe static void WriteInt32 (IntPtr ptr, int ofs, int val)
1224 byte *addr = ((byte *) ptr) + ofs;
1226 if (((uint)addr & 3) == 0)
1229 String.memcpy (addr, (byte*)&val, 4);
1234 [SuppressUnmanagedCodeSecurity]
1235 public static void WriteInt32([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, int val)
1237 throw new NotImplementedException ();
1240 public static unsafe void WriteInt64 (IntPtr ptr, long val)
1242 byte *addr = (byte *) ptr;
1244 // The real alignment might be 4 on some platforms, but this is just an optimization,
1245 // so it doesn't matter.
1246 if (((uint)addr & 7) == 0)
1249 String.memcpy (addr, (byte*)&val, 8);
1252 public static unsafe void WriteInt64 (IntPtr ptr, int ofs, long val)
1254 byte *addr = ((byte *) ptr) + ofs;
1256 // The real alignment might be 4 on some platforms, but this is just an optimization,
1257 // so it doesn't matter.
1258 if (((uint)addr & 7) == 0)
1261 String.memcpy (addr, (byte*)&val, 8);
1265 [SuppressUnmanagedCodeSecurity]
1266 public static void WriteInt64 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, long val)
1268 throw new NotImplementedException ();
1271 public static void WriteIntPtr (IntPtr ptr, IntPtr val)
1273 if (IntPtr.Size == 4)
1274 WriteInt32 (ptr, (int)val);
1276 WriteInt64 (ptr, (long)val);
1279 public static void WriteIntPtr (IntPtr ptr, int ofs, IntPtr val)
1281 if (IntPtr.Size == 4)
1282 WriteInt32 (ptr, ofs, (int)val);
1284 WriteInt64 (ptr, ofs, (long)val);
1288 public static void WriteIntPtr([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, IntPtr val)
1290 throw new NotImplementedException ();
1293 private static Exception ConvertHrToException (int errorCode)
1295 const int MSEE_E_APPDOMAINUNLOADED = unchecked ((int)0x80131014L);
1296 const int COR_E_APPLICATION = unchecked ((int)0x80131600L);
1297 const int E_INVALIDARG = unchecked ((int)0x80070057);
1298 const int COR_E_ARGUMENTOUTOFRANGE = unchecked ((int)0x80131502L);
1299 const int COR_E_ARITHMETIC = unchecked ((int)0x80070216);
1300 const int COR_E_ARRAYTYPEMISMATCH = unchecked ((int)0x80131503L);
1301 const int COR_E_BADIMAGEFORMAT = unchecked ((int)0x8007000BL);
1302 const int ERROR_BAD_FORMAT = unchecked ((int)0x0B);
1303 //const int COR_E_COMEMULATE_ERROR = unchecked ((int)?);
1304 const int COR_E_CONTEXTMARSHAL = unchecked ((int)0x80131504L);
1305 //const int COR_E_CORE = unchecked ((int)?);
1306 const int NTE_FAIL = unchecked ((int)0x80090020L);
1307 const int COR_E_DIRECTORYNOTFOUND = unchecked ((int)0x80070003L);
1308 const int ERROR_PATH_NOT_FOUND = unchecked ((int)0x03);
1309 const int COR_E_DIVIDEBYZERO = unchecked ((int)0x80020012L);
1310 const int COR_E_DUPLICATEWAITOBJECT = unchecked ((int)0x80131529L);
1311 const int COR_E_ENDOFSTREAM = unchecked ((int)0x80070026L);
1312 const int COR_E_TYPELOAD = unchecked ((int)0x80131522L);
1313 const int COR_E_EXCEPTION = unchecked ((int)0x80131500L);
1314 const int COR_E_EXECUTIONENGINE = unchecked ((int)0x80131506L);
1315 const int COR_E_FIELDACCESS = unchecked ((int)0x80131507L);
1316 const int COR_E_FILENOTFOUND = unchecked ((int)0x80070002L);
1317 const int ERROR_FILE_NOT_FOUND = unchecked ((int)0x02);
1318 const int COR_E_FORMAT = unchecked ((int)0x80131537L);
1319 const int COR_E_INDEXOUTOFRANGE = unchecked ((int)0x80131508L);
1320 const int COR_E_INVALIDCAST = unchecked ((int)0x80004002L);
1321 const int COR_E_INVALIDCOMOBJECT = unchecked ((int)0x80131527L);
1322 const int COR_E_INVALIDFILTERCRITERIA = unchecked ((int)0x80131601L);
1323 const int COR_E_INVALIDOLEVARIANTTYPE = unchecked ((int)0x80131531L);
1324 const int COR_E_INVALIDOPERATION = unchecked ((int)0x80131509L);
1325 const int COR_E_IO = unchecked ((int)0x80131620L);
1326 const int COR_E_MEMBERACCESS = unchecked ((int)0x8013151AL);
1327 const int COR_E_METHODACCESS = unchecked ((int)0x80131510L);
1328 const int COR_E_MISSINGFIELD = unchecked ((int)0x80131511L);
1329 const int COR_E_MISSINGMANIFESTRESOURCE = unchecked ((int)0x80131532L);
1330 const int COR_E_MISSINGMEMBER = unchecked ((int)0x80131512L);
1331 const int COR_E_MISSINGMETHOD = unchecked ((int)0x80131513L);
1332 const int COR_E_MULTICASTNOTSUPPORTED = unchecked ((int)0x80131514L);
1333 const int COR_E_NOTFINITENUMBER = unchecked ((int)0x80131528L);
1334 const int E_NOTIMPL = unchecked ((int)0x80004001L);
1335 const int COR_E_NOTSUPPORTED = unchecked ((int)0x80131515L);
1336 const int COR_E_NULLREFERENCE = unchecked ((int)0x80004003L);
1337 const int E_OUTOFMEMORY = unchecked ((int)0x8007000EL);
1338 const int COR_E_OVERFLOW = unchecked ((int)0x80131516L);
1339 const int COR_E_PATHTOOLONG = unchecked ((int)0x800700CEL);
1340 const int ERROR_FILENAME_EXCED_RANGE = unchecked ((int)0xCE);
1341 const int COR_E_RANK = unchecked ((int)0x80131517L);
1342 const int COR_E_REFLECTIONTYPELOAD = unchecked ((int)0x80131602L);
1343 const int COR_E_REMOTING = unchecked ((int)0x8013150BL);
1344 const int COR_E_SAFEARRAYTYPEMISMATCH = unchecked ((int)0x80131533L);
1345 const int COR_E_SECURITY = unchecked ((int)0x8013150AL);
1346 const int COR_E_SERIALIZATION = unchecked ((int)0x8013150CL);
1347 const int COR_E_STACKOVERFLOW = unchecked ((int)0x800703E9L);
1348 const int ERROR_STACK_OVERFLOW = unchecked ((int)0x03E9);
1349 const int COR_E_SYNCHRONIZATIONLOCK = unchecked ((int)0x80131518L);
1350 const int COR_E_SYSTEM = unchecked ((int)0x80131501L);
1351 const int COR_E_TARGET = unchecked ((int)0x80131603L);
1352 const int COR_E_TARGETINVOCATION = unchecked ((int)0x80131604L);
1353 const int COR_E_TARGETPARAMCOUNT = unchecked ((int)0x8002000EL);
1354 const int COR_E_THREADABORTED = unchecked ((int)0x80131530L);
1355 const int COR_E_THREADINTERRUPTED = unchecked ((int)0x80131519L);
1356 const int COR_E_THREADSTATE = unchecked ((int)0x80131520L);
1357 const int COR_E_THREADSTOP = unchecked ((int)0x80131521L);
1358 const int COR_E_TYPEINITIALIZATION = unchecked ((int)0x80131534L);
1359 const int COR_E_VERIFICATION = unchecked ((int)0x8013150DL);
1360 //const int COR_E_WEAKREFERENCE = unchecked ((int)?);
1361 //const int COR_E_VTABLECALLSNOTSUPPORTED = unchecked ((int));
1363 switch (errorCode) {
1364 case MSEE_E_APPDOMAINUNLOADED:
1365 return new AppDomainUnloadedException ();
1366 case COR_E_APPLICATION:
1367 return new ApplicationException ();
1369 return new ArgumentException ();
1370 case COR_E_ARGUMENTOUTOFRANGE:
1371 return new ArgumentOutOfRangeException ();
1372 case COR_E_ARITHMETIC:
1373 return new ArithmeticException ();
1374 case COR_E_ARRAYTYPEMISMATCH:
1375 return new ArrayTypeMismatchException ();
1376 case COR_E_BADIMAGEFORMAT:
1377 case ERROR_BAD_FORMAT:
1378 return new BadImageFormatException ();
1379 // case COR_E_COMEMULATE_ERROR:
1380 // return new COMEmulateException ();
1381 case COR_E_CONTEXTMARSHAL:
1382 return new ContextMarshalException ();
1384 // return new CoreException ();
1386 return new System.Security.Cryptography.CryptographicException ();
1387 case COR_E_DIRECTORYNOTFOUND:
1388 case ERROR_PATH_NOT_FOUND:
1389 return new System.IO.DirectoryNotFoundException ();
1390 case COR_E_DIVIDEBYZERO:
1391 return new DivideByZeroException ();
1392 case COR_E_DUPLICATEWAITOBJECT:
1393 return new DuplicateWaitObjectException ();
1394 case COR_E_ENDOFSTREAM:
1395 return new System.IO.EndOfStreamException ();
1396 case COR_E_EXCEPTION:
1397 return new Exception ();
1398 case COR_E_EXECUTIONENGINE:
1399 return new ExecutionEngineException ();
1400 case COR_E_FIELDACCESS:
1401 return new FieldAccessException ();
1402 case COR_E_FILENOTFOUND:
1403 case ERROR_FILE_NOT_FOUND:
1404 return new System.IO.FileNotFoundException ();
1406 return new FormatException ();
1407 case COR_E_INDEXOUTOFRANGE:
1408 return new IndexOutOfRangeException ();
1409 case COR_E_INVALIDCAST:
1410 // E_NOINTERFACE has same value as COR_E_INVALIDCAST
1411 return new InvalidCastException ();
1412 case COR_E_INVALIDCOMOBJECT:
1413 return new InvalidComObjectException ();
1414 case COR_E_INVALIDFILTERCRITERIA:
1415 return new InvalidFilterCriteriaException ();
1416 case COR_E_INVALIDOLEVARIANTTYPE:
1417 return new InvalidOleVariantTypeException ();
1418 case COR_E_INVALIDOPERATION:
1419 return new InvalidOperationException ();
1421 return new System.IO.IOException ();
1422 case COR_E_MEMBERACCESS:
1423 return new MemberAccessException ();
1424 case COR_E_METHODACCESS:
1425 return new MethodAccessException ();
1426 case COR_E_MISSINGFIELD:
1427 return new MissingFieldException ();
1428 case COR_E_MISSINGMANIFESTRESOURCE:
1429 return new System.Resources.MissingManifestResourceException ();
1430 case COR_E_MISSINGMEMBER:
1431 return new MissingMemberException ();
1432 case COR_E_MISSINGMETHOD:
1433 return new MissingMethodException ();
1434 case COR_E_MULTICASTNOTSUPPORTED:
1435 return new MulticastNotSupportedException ();
1436 case COR_E_NOTFINITENUMBER:
1437 return new NotFiniteNumberException ();
1439 return new NotImplementedException ();
1440 case COR_E_NOTSUPPORTED:
1441 return new NotSupportedException ();
1442 case COR_E_NULLREFERENCE:
1443 // E_POINTER has the same value as COR_E_NULLREFERENCE
1444 return new NullReferenceException ();
1446 // COR_E_OUTOFMEMORY has the same value as E_OUTOFMEMORY
1447 return new OutOfMemoryException ();
1448 case COR_E_OVERFLOW:
1449 return new OverflowException ();
1450 case COR_E_PATHTOOLONG:
1451 case ERROR_FILENAME_EXCED_RANGE:
1452 return new System.IO.PathTooLongException ();
1454 return new RankException ();
1455 case COR_E_REFLECTIONTYPELOAD:
1456 return new System.Reflection.ReflectionTypeLoadException (new Type[] { }, new Exception[] { });
1457 case COR_E_REMOTING:
1458 return new System.Runtime.Remoting.RemotingException ();
1459 case COR_E_SAFEARRAYTYPEMISMATCH:
1460 return new SafeArrayTypeMismatchException ();
1461 case COR_E_SECURITY:
1462 return new SecurityException ();
1463 case COR_E_SERIALIZATION:
1464 return new System.Runtime.Serialization.SerializationException ();
1465 case COR_E_STACKOVERFLOW:
1466 case ERROR_STACK_OVERFLOW:
1467 return new StackOverflowException ();
1468 case COR_E_SYNCHRONIZATIONLOCK:
1469 return new SynchronizationLockException ();
1471 return new SystemException ();
1473 return new TargetException ();
1474 case COR_E_TARGETINVOCATION:
1475 return new System.Reflection.TargetInvocationException (null);
1476 case COR_E_TARGETPARAMCOUNT:
1477 return new TargetParameterCountException ();
1478 // case COR_E_THREADABORTED:
1479 // ThreadAbortException c'tor is inaccessible
1480 // return new System.Threading.ThreadAbortException ();
1481 case COR_E_THREADINTERRUPTED:
1482 return new ThreadInterruptedException ();
1483 case COR_E_THREADSTATE:
1484 return new ThreadStateException ();
1485 // case COR_E_THREADSTOP:
1486 // ThreadStopException does not exist
1487 // return new System.Threading.ThreadStopException ();
1488 case COR_E_TYPELOAD:
1489 return new TypeLoadException ();
1490 // MSDN lists COR_E_TYPELOAD twice with different exceptions.
1491 // return new EntryPointNotFoundException ();
1492 case COR_E_TYPEINITIALIZATION:
1493 return new TypeInitializationException("", null);
1494 case COR_E_VERIFICATION:
1495 return new VerificationException ();
1496 // case COR_E_WEAKREFERENCE:
1497 // return new WeakReferenceException ();
1498 // case COR_E_VTABLECALLSNOTSUPPORTED:
1499 // return new VTableCallsNotSupportedException ();
1502 return new COMException ("", errorCode);
1506 [DllImport ("oleaut32.dll", CharSet=CharSet.Unicode, EntryPoint = "SetErrorInfo")]
1507 static extern int _SetErrorInfo (int dwReserved,
1508 [MarshalAs(UnmanagedType.Interface)] IErrorInfo pIErrorInfo);
1510 [DllImport ("oleaut32.dll", CharSet=CharSet.Unicode, EntryPoint = "GetErrorInfo")]
1511 static extern int _GetErrorInfo (int dwReserved,
1512 [MarshalAs(UnmanagedType.Interface)] out IErrorInfo ppIErrorInfo);
1514 static bool SetErrorInfoNotAvailable;
1515 static bool GetErrorInfoNotAvailable;
1517 internal static int SetErrorInfo (int dwReserved, IErrorInfo errorInfo)
1522 if (SetErrorInfoNotAvailable)
1526 retVal = _SetErrorInfo (dwReserved, errorInfo);
1529 // ignore any exception - probably there's no suitable SetErrorInfo
1530 // method available.
1531 SetErrorInfoNotAvailable = true;
1536 internal static int GetErrorInfo (int dwReserved, out IErrorInfo errorInfo)
1541 if (GetErrorInfoNotAvailable)
1545 retVal = _GetErrorInfo (dwReserved, out errorInfo);
1548 // ignore any exception - probably there's no suitable GetErrorInfo
1549 // method available.
1550 GetErrorInfoNotAvailable = true;
1555 public static Exception GetExceptionForHR (int errorCode)
1557 return GetExceptionForHR (errorCode, IntPtr.Zero);
1560 public static Exception GetExceptionForHR (int errorCode, IntPtr errorInfo)
1563 IErrorInfo info = null;
1564 if (errorInfo != (IntPtr)(-1)) {
1565 if (errorInfo == IntPtr.Zero) {
1566 if (GetErrorInfo (0, out info) != 0) {
1570 info = Marshal.GetObjectForIUnknown (errorInfo) as IErrorInfo;
1574 if (info is ManagedErrorInfo && ((ManagedErrorInfo) info).Exception.hresult == errorCode) {
1575 return ((ManagedErrorInfo) info).Exception;
1578 Exception e = ConvertHrToException (errorCode);
1579 if (info != null && e != null) {
1581 info.GetHelpContext (out helpContext);
1583 info.GetSource (out str);
1585 info.GetDescription (out str);
1587 info.GetHelpFile (out str);
1589 if (helpContext == 0) {
1592 e.HelpLink = string.Format ("{0}#{1}", str, helpContext);
1597 return ConvertHrToException (errorCode);
1601 #if !FULL_AOT_RUNTIME
1602 public static int FinalReleaseComObject (object o)
1604 while (ReleaseComObject (o) != 0);
1609 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1610 private static extern Delegate GetDelegateForFunctionPointerInternal (IntPtr ptr, Type t);
1612 public static Delegate GetDelegateForFunctionPointer (IntPtr ptr, Type t)
1615 throw new ArgumentNullException ("t");
1616 if (!t.IsSubclassOf (typeof (MulticastDelegate)) || (t == typeof (MulticastDelegate)))
1617 throw new ArgumentException ("Type is not a delegate", "t");
1618 if (t.IsGenericType)
1619 throw new ArgumentException ("The specified Type must not be a generic type definition.");
1620 if (ptr == IntPtr.Zero)
1621 throw new ArgumentNullException ("ptr");
1623 return GetDelegateForFunctionPointerInternal (ptr, t);
1626 public static TDelegate GetDelegateForFunctionPointer<TDelegate> (IntPtr ptr) {
1627 return (TDelegate) (object) GetDelegateForFunctionPointer (ptr, typeof (TDelegate));
1630 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1631 private static extern IntPtr GetFunctionPointerForDelegateInternal (Delegate d);
1633 public static IntPtr GetFunctionPointerForDelegate (Delegate d)
1636 throw new ArgumentNullException ("d");
1638 return GetFunctionPointerForDelegateInternal (d);
1641 public static IntPtr GetFunctionPointerForDelegate<TDelegate> (TDelegate d) {
1643 throw new ArgumentNullException ("d");
1645 return GetFunctionPointerForDelegateInternal ((Delegate)(object)d);