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 #if FEATURE_COMINTEROP
412 var errorInfo = new ManagedErrorInfo(e);
413 SetErrorInfo (0, errorInfo);
422 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
423 public static int GetHRForLastWin32Error()
425 throw new NotImplementedException ();
428 [MethodImplAttribute (MethodImplOptions.InternalCall)]
429 private extern static IntPtr GetIDispatchForObjectInternal (object o);
431 public static IntPtr GetIDispatchForObject (object o)
433 IntPtr pUnk = GetIDispatchForObjectInternal (o);
434 // Internal method does not AddRef
440 public static IntPtr GetIDispatchForObjectInContext (object o)
442 throw new NotImplementedException ();
446 public static IntPtr GetITypeInfoForType (Type t)
448 throw new NotImplementedException ();
451 [MethodImplAttribute (MethodImplOptions.InternalCall)]
452 private extern static IntPtr GetIUnknownForObjectInternal (object o);
454 public static IntPtr GetIUnknownForObject (object o)
456 IntPtr pUnk = GetIUnknownForObjectInternal (o);
457 // Internal method does not AddRef
463 public static IntPtr GetIUnknownForObjectInContext (object o)
465 throw new NotImplementedException ();
469 [Obsolete ("This method has been deprecated")]
470 public static IntPtr GetManagedThunkForUnmanagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
472 throw new NotImplementedException ();
476 public static MemberInfo GetMethodInfoForComSlot (Type t, int slot, ref ComMemberType memberType)
478 throw new NotImplementedException ();
481 public static void GetNativeVariantForObject (object obj, IntPtr pDstNativeVariant)
483 Variant vt = new Variant();
485 Marshal.StructureToPtr(vt, pDstNativeVariant, false);
488 public static void GetNativeVariantForObject<T> (T obj, IntPtr pDstNativeVariant) {
489 GetNativeVariantForObject ((object)obj, pDstNativeVariant);
493 [MethodImplAttribute (MethodImplOptions.InternalCall)]
494 private static extern object GetObjectForCCW (IntPtr pUnk);
497 public static object GetObjectForIUnknown (IntPtr pUnk)
500 object obj = GetObjectForCCW (pUnk);
503 ComInteropProxy proxy = ComInteropProxy.GetProxy (pUnk, typeof (__ComObject));
504 obj = proxy.GetTransparentProxy ();
508 throw new NotImplementedException ();
512 public static object GetObjectForNativeVariant (IntPtr pSrcNativeVariant)
514 Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
515 return vt.GetValue();
518 public static T GetObjectForNativeVariant<T> (IntPtr pSrcNativeVariant) {
519 Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
520 return (T)vt.GetValue();
523 public static object[] GetObjectsForNativeVariants (IntPtr aSrcNativeVariant, int cVars)
526 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
527 object[] objects = new object[cVars];
528 for (int i = 0; i < cVars; i++)
529 objects[i] = GetObjectForNativeVariant ((IntPtr)(aSrcNativeVariant.ToInt64 () +
530 i * SizeOf (typeof(Variant))));
534 public static T[] GetObjectsForNativeVariants<T> (IntPtr aSrcNativeVariant, int cVars) {
536 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
537 T[] objects = new T[cVars];
538 for (int i = 0; i < cVars; i++)
539 objects[i] = GetObjectForNativeVariant<T> ((IntPtr)(aSrcNativeVariant.ToInt64 () +
540 i * SizeOf (typeof(Variant))));
545 public static int GetStartComSlot (Type t)
547 throw new NotImplementedException ();
551 [Obsolete ("This method has been deprecated")]
552 public static Thread GetThreadFromFiberCookie (int cookie)
554 throw new NotImplementedException ();
557 public static object GetTypedObjectForIUnknown (IntPtr pUnk, Type t)
559 ComInteropProxy proxy = new ComInteropProxy (pUnk, t);
560 __ComObject co = (__ComObject)proxy.GetTransparentProxy ();
561 foreach (Type itf in t.GetInterfaces ()) {
562 if ((itf.Attributes & TypeAttributes.Import) == TypeAttributes.Import) {
563 if (co.GetInterface (itf) == IntPtr.Zero)
571 public static Type GetTypeForITypeInfo (IntPtr piTypeInfo)
573 throw new NotImplementedException ();
576 public static Type GetTypeFromCLSID (Guid clsid)
578 throw new NotImplementedException ();
581 #if !FULL_AOT_RUNTIME
584 public static string GetTypeInfoName (UCOMITypeInfo pTI)
586 throw new NotImplementedException ();
589 public static string GetTypeInfoName (ITypeInfo typeInfo)
591 throw new NotImplementedException ();
596 public static Guid GetTypeLibGuid (UCOMITypeLib pTLB)
598 throw new NotImplementedException ();
602 public static Guid GetTypeLibGuid (ITypeLib typelib)
604 throw new NotImplementedException ();
608 public static Guid GetTypeLibGuidForAssembly (Assembly asm)
610 throw new NotImplementedException ();
615 public static int GetTypeLibLcid (UCOMITypeLib pTLB)
617 throw new NotImplementedException ();
621 public static int GetTypeLibLcid (ITypeLib typelib)
623 throw new NotImplementedException ();
628 public static string GetTypeLibName (UCOMITypeLib pTLB)
630 throw new NotImplementedException ();
634 public static string GetTypeLibName (ITypeLib typelib)
636 throw new NotImplementedException ();
640 public static void GetTypeLibVersionForAssembly (Assembly inputAssembly, out int majorVersion, out int minorVersion)
642 throw new NotImplementedException ();
645 public static object GetUniqueObjectForIUnknown (IntPtr unknown)
647 throw new NotImplementedException ();
652 [Obsolete ("This method has been deprecated")]
653 public static IntPtr GetUnmanagedThunkForManagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
655 throw new NotImplementedException ();
659 [MethodImplAttribute (MethodImplOptions.InternalCall)]
660 public extern static bool IsComObject (object o);
662 public static bool IsComObject (object o)
664 throw new NotImplementedException ();
669 public static bool IsTypeVisibleFromCom (Type t)
671 throw new NotImplementedException ();
675 public static int NumParamBytes (MethodInfo m)
677 throw new NotImplementedException ();
681 [MethodImplAttribute(MethodImplOptions.InternalCall)]
682 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
683 public static extern int GetLastWin32Error();
685 [MethodImplAttribute(MethodImplOptions.InternalCall)]
686 public extern static IntPtr OffsetOf (Type t, string fieldName);
688 public static IntPtr OffsetOf<T> (string fieldName) {
689 return OffsetOf (typeof (T), fieldName);
692 [MethodImplAttribute(MethodImplOptions.InternalCall)]
693 public extern static void Prelink (MethodInfo m);
695 [MethodImplAttribute(MethodImplOptions.InternalCall)]
696 public extern static void PrelinkAll (Type c);
698 [MethodImplAttribute(MethodImplOptions.InternalCall)]
699 public extern static string PtrToStringAnsi (IntPtr ptr);
701 [MethodImplAttribute(MethodImplOptions.InternalCall)]
702 public extern static string PtrToStringAnsi (IntPtr ptr, int len);
704 public static string PtrToStringAuto (IntPtr ptr)
706 return SystemDefaultCharSize == 2
707 ? PtrToStringUni (ptr) : PtrToStringAnsi (ptr);
710 public static string PtrToStringAuto (IntPtr ptr, int len)
712 return SystemDefaultCharSize == 2
713 ? PtrToStringUni (ptr, len) : PtrToStringAnsi (ptr, len);
716 [MethodImplAttribute(MethodImplOptions.InternalCall)]
717 public extern static string PtrToStringUni (IntPtr ptr);
719 [MethodImplAttribute(MethodImplOptions.InternalCall)]
720 public extern static string PtrToStringUni (IntPtr ptr, int len);
723 [MethodImplAttribute(MethodImplOptions.InternalCall)]
724 public extern static string PtrToStringBSTR (IntPtr ptr);
726 public static string PtrToStringBSTR (IntPtr ptr)
728 throw new NotImplementedException ();
732 [MethodImplAttribute(MethodImplOptions.InternalCall)]
734 public extern static void PtrToStructure (IntPtr ptr, object structure);
736 [MethodImplAttribute(MethodImplOptions.InternalCall)]
738 public extern static object PtrToStructure (IntPtr ptr, Type structureType);
740 public static void PtrToStructure<T> (IntPtr ptr, T structure) {
741 PtrToStructure (ptr, (object)structure);
744 public static T PtrToStructure<T> (IntPtr ptr) {
745 return (T) PtrToStructure (ptr, typeof (T));
749 [MethodImplAttribute (MethodImplOptions.InternalCall)]
750 private extern static int QueryInterfaceInternal (IntPtr pUnk, ref Guid iid, out IntPtr ppv);
753 public static int QueryInterface (IntPtr pUnk, ref Guid iid, out IntPtr ppv)
756 if (pUnk == IntPtr.Zero)
757 throw new ArgumentException ("Value cannot be null.", "pUnk");
758 return QueryInterfaceInternal (pUnk, ref iid, out ppv);
760 throw new NotImplementedException ();
764 public static byte ReadByte (IntPtr ptr)
771 public static byte ReadByte (IntPtr ptr, int ofs) {
773 return *((byte*)ptr + ofs);
778 [SuppressUnmanagedCodeSecurity]
779 public static byte ReadByte ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
781 throw new NotImplementedException ();
784 public unsafe static short ReadInt16 (IntPtr ptr)
786 byte *addr = (byte *) ptr;
788 // The mono JIT can't inline this due to the hight number of calls
789 // return ReadInt16 (ptr, 0);
791 if (((uint)addr & 1) == 0)
792 return *(short*)addr;
795 Buffer.Memcpy ((byte*)&s, (byte*)ptr, 2);
799 public unsafe static short ReadInt16 (IntPtr ptr, int ofs)
801 byte *addr = ((byte *) ptr) + ofs;
803 if (((uint) addr & 1) == 0)
804 return *(short*)addr;
807 Buffer.Memcpy ((byte*)&s, addr, 2);
812 [SuppressUnmanagedCodeSecurity]
813 public static short ReadInt16 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
815 throw new NotImplementedException ();
818 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
819 public unsafe static int ReadInt32 (IntPtr ptr)
821 byte *addr = (byte *) ptr;
823 if (((uint)addr & 3) == 0)
827 Buffer.Memcpy ((byte*)&s, addr, 4);
831 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
832 public unsafe static int ReadInt32 (IntPtr ptr, int ofs)
834 byte *addr = ((byte *) ptr) + ofs;
836 if ((((int) addr) & 3) == 0)
840 Buffer.Memcpy ((byte*)&s, addr, 4);
845 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
847 [SuppressUnmanagedCodeSecurity]
848 public static int ReadInt32 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
850 throw new NotImplementedException ();
853 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
854 public unsafe static long ReadInt64 (IntPtr ptr)
856 byte *addr = (byte *) ptr;
858 // The real alignment might be 4 on some platforms, but this is just an optimization,
859 // so it doesn't matter.
860 if (((uint) addr & 7) == 0)
864 Buffer.Memcpy ((byte*)&s, addr, 8);
868 public unsafe static long ReadInt64 (IntPtr ptr, int ofs)
870 byte *addr = ((byte *) ptr) + ofs;
872 if (((uint) addr & 7) == 0)
876 Buffer.Memcpy ((byte*)&s, addr, 8);
880 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
882 [SuppressUnmanagedCodeSecurity]
883 public static long ReadInt64 ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
885 throw new NotImplementedException ();
888 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
889 public static IntPtr ReadIntPtr (IntPtr ptr)
891 if (IntPtr.Size == 4)
892 return (IntPtr)ReadInt32 (ptr);
894 return (IntPtr)ReadInt64 (ptr);
897 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
898 public static IntPtr ReadIntPtr (IntPtr ptr, int ofs)
900 if (IntPtr.Size == 4)
901 return (IntPtr)ReadInt32 (ptr, ofs);
903 return (IntPtr)ReadInt64 (ptr, ofs);
906 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
908 public static IntPtr ReadIntPtr ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
910 throw new NotImplementedException ();
913 [MethodImplAttribute (MethodImplOptions.InternalCall)]
914 public extern static IntPtr ReAllocCoTaskMem (IntPtr pv, int cb);
916 [MethodImplAttribute(MethodImplOptions.InternalCall)]
917 public extern static IntPtr ReAllocHGlobal (IntPtr pv, IntPtr cb);
920 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
921 [MethodImplAttribute (MethodImplOptions.InternalCall)]
922 private extern static int ReleaseInternal (IntPtr pUnk);
925 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
926 public static int Release (IntPtr pUnk)
929 if (pUnk == IntPtr.Zero)
930 throw new ArgumentException ("Value cannot be null.", "pUnk");
932 return ReleaseInternal (pUnk);
934 throw new NotImplementedException ();
938 #if !FULL_AOT_RUNTIME
939 [MethodImplAttribute (MethodImplOptions.InternalCall)]
940 private extern static int ReleaseComObjectInternal (object co);
942 public static int ReleaseComObject (object o)
945 throw new ArgumentException ("Value cannot be null.", "o");
946 if (!IsComObject (o))
947 throw new ArgumentException ("Value must be a Com object.", "o");
948 return ReleaseComObjectInternal (o);
953 public static void ReleaseThreadCache()
955 throw new NotImplementedException ();
958 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
959 public static bool SetComObjectData (object obj, object key, object data)
961 throw new NotSupportedException ("MSDN states user code should never need to call this method.");
966 public static int SizeOf (object structure)
968 return SizeOf (structure.GetType ());
971 [MethodImplAttribute(MethodImplOptions.InternalCall)]
972 public extern static int SizeOf (Type t);
974 public static int SizeOf<T> () {
975 return SizeOf (typeof (T));
978 public static int SizeOf<T> (T structure) {
979 return SizeOf (structure.GetType ());
982 internal static uint SizeOfType (Type type)
984 return (uint) SizeOf (type);
987 internal static uint AlignedSizeOf<T> () where T : struct
989 uint size = SizeOfType (typeof (T));
990 if (size == 1 || size == 2)
992 if (IntPtr.Size == 8 && size == 4)
994 return (size + 3) & (~((uint)3));
997 [MethodImplAttribute(MethodImplOptions.InternalCall)]
998 public extern static IntPtr StringToBSTR (string s);
1001 // I believe this is wrong, because in Mono and in P/Invoke
1002 // we treat "Ansi" conversions as UTF-8 conversions, while
1003 // this one does not do this
1005 public static IntPtr StringToCoTaskMemAnsi (string s)
1007 int length = s.Length + 1;
1008 IntPtr ctm = AllocCoTaskMem (length);
1010 byte[] asBytes = new byte[length];
1011 for (int i = 0; i < s.Length; i++)
1012 asBytes[i] = (byte)s[i];
1013 asBytes[s.Length] = 0;
1015 copy_to_unmanaged (asBytes, 0, ctm, length);
1019 public static IntPtr StringToCoTaskMemAuto (string s)
1021 return SystemDefaultCharSize == 2
1022 ? StringToCoTaskMemUni (s) : StringToCoTaskMemAnsi (s);
1025 public static IntPtr StringToCoTaskMemUni (string s)
1027 int length = s.Length + 1;
1028 IntPtr ctm = AllocCoTaskMem (length * 2);
1030 char[] asChars = new char[length];
1031 s.CopyTo (0, asChars, 0, s.Length);
1032 asChars[s.Length] = '\0';
1034 copy_to_unmanaged (asChars, 0, ctm, length);
1038 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1039 public extern static IntPtr StringToHGlobalAnsi (string s);
1041 public static IntPtr StringToHGlobalAuto (string s)
1043 return SystemDefaultCharSize == 2
1044 ? StringToHGlobalUni (s) : StringToHGlobalAnsi (s);
1047 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1048 public extern static IntPtr StringToHGlobalUni (string s);
1050 public static IntPtr SecureStringToBSTR (SecureString s)
1053 throw new ArgumentNullException ("s");
1055 IntPtr ctm = AllocCoTaskMem ((len+1) * 2 + 4);
1056 byte [] buffer = null;
1057 WriteInt32 (ctm, 0, len*2);
1059 buffer = s.GetBuffer ();
1061 for (int i = 0; i < len; i++)
1062 WriteInt16 (ctm, 4 + (i * 2), (short) ((buffer [(i*2)] << 8) | (buffer [i*2+1])));
1063 WriteInt16 (ctm, 4 + buffer.Length, 0);
1066 for (int i = buffer.Length; i > 0; ){
1071 return (IntPtr) ((long)ctm + 4);
1074 public static IntPtr SecureStringToCoTaskMemAnsi (SecureString s)
1077 throw new ArgumentNullException ("s");
1079 IntPtr ctm = AllocCoTaskMem (len + 1);
1080 byte [] copy = new byte [len+1];
1083 byte [] buffer = s.GetBuffer ();
1085 for (; i < len; i++, j += 2){
1086 copy [i] = buffer [j+1];
1091 copy_to_unmanaged (copy, 0, ctm, len+1);
1093 // Ensure that we clear the buffer.
1094 for (int i = len; i > 0; ){
1102 public static IntPtr SecureStringToCoTaskMemUnicode (SecureString s)
1105 throw new ArgumentNullException ("s");
1107 IntPtr ctm = AllocCoTaskMem (len * 2 + 2);
1108 byte [] buffer = null;
1110 buffer = s.GetBuffer ();
1111 for (int i = 0; i < len; i++)
1112 WriteInt16 (ctm, i * 2, (short) ((buffer [(i*2)] << 8) | (buffer [i*2+1])));
1113 WriteInt16 (ctm, buffer.Length, 0);
1116 for (int i = buffer.Length; i > 0; ){
1124 public static IntPtr SecureStringToGlobalAllocAnsi (SecureString s)
1127 throw new ArgumentNullException ("s");
1128 return SecureStringToCoTaskMemAnsi (s);
1131 public static IntPtr SecureStringToGlobalAllocUnicode (SecureString s)
1134 throw new ArgumentNullException ("s");
1135 return SecureStringToCoTaskMemUnicode (s);
1138 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
1140 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1141 public extern static void StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld);
1143 public static void StructureToPtr<T> (T structure, IntPtr ptr, bool fDeleteOld) {
1144 StructureToPtr ((object)structure, ptr, fDeleteOld);
1147 public static void ThrowExceptionForHR (int errorCode) {
1148 Exception ex = GetExceptionForHR (errorCode);
1153 public static void ThrowExceptionForHR (int errorCode, IntPtr errorInfo) {
1154 Exception ex = GetExceptionForHR (errorCode, errorInfo);
1159 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1160 public extern static IntPtr UnsafeAddrOfPinnedArrayElement (Array arr, int index);
1162 public static IntPtr UnsafeAddrOfPinnedArrayElement<T> (T[] arr, int index) {
1163 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 Buffer.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 Buffer.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 Buffer.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 Buffer.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 Buffer.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 Buffer.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 #if FEATURE_COMINTEROP
1526 [DllImport ("oleaut32.dll", CharSet=CharSet.Unicode, EntryPoint = "SetErrorInfo")]
1527 static extern int _SetErrorInfo (int dwReserved,
1528 [MarshalAs(UnmanagedType.Interface)] IErrorInfo pIErrorInfo);
1530 [DllImport ("oleaut32.dll", CharSet=CharSet.Unicode, EntryPoint = "GetErrorInfo")]
1531 static extern int _GetErrorInfo (int dwReserved,
1532 [MarshalAs(UnmanagedType.Interface)] out IErrorInfo ppIErrorInfo);
1534 static bool SetErrorInfoNotAvailable;
1535 static bool GetErrorInfoNotAvailable;
1537 internal static int SetErrorInfo (int dwReserved, IErrorInfo errorInfo)
1542 if (SetErrorInfoNotAvailable)
1546 retVal = _SetErrorInfo (dwReserved, errorInfo);
1549 // ignore any exception - probably there's no suitable SetErrorInfo
1550 // method available.
1551 SetErrorInfoNotAvailable = true;
1556 internal static int GetErrorInfo (int dwReserved, out IErrorInfo errorInfo)
1561 if (GetErrorInfoNotAvailable)
1565 retVal = _GetErrorInfo (dwReserved, out errorInfo);
1568 // ignore any exception - probably there's no suitable GetErrorInfo
1569 // method available.
1570 GetErrorInfoNotAvailable = true;
1575 public static Exception GetExceptionForHR (int errorCode)
1577 return GetExceptionForHR (errorCode, IntPtr.Zero);
1580 public static Exception GetExceptionForHR (int errorCode, IntPtr errorInfo)
1582 #if FEATURE_COMINTEROP
1583 IErrorInfo info = null;
1584 if (errorInfo != (IntPtr)(-1)) {
1585 if (errorInfo == IntPtr.Zero) {
1586 if (GetErrorInfo (0, out info) != 0) {
1590 info = Marshal.GetObjectForIUnknown (errorInfo) as IErrorInfo;
1594 if (info is ManagedErrorInfo && ((ManagedErrorInfo) info).Exception._HResult == errorCode) {
1595 return ((ManagedErrorInfo) info).Exception;
1598 Exception e = ConvertHrToException (errorCode);
1599 if (info != null && e != null) {
1601 info.GetHelpContext (out helpContext);
1603 info.GetSource (out str);
1605 info.GetDescription (out str);
1607 info.GetHelpFile (out str);
1609 if (helpContext == 0) {
1612 e.HelpLink = string.Format ("{0}#{1}", str, helpContext);
1617 return ConvertHrToException (errorCode);
1621 #if !FULL_AOT_RUNTIME
1622 public static int FinalReleaseComObject (object o)
1624 while (ReleaseComObject (o) != 0);
1629 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1630 private static extern Delegate GetDelegateForFunctionPointerInternal (IntPtr ptr, Type t);
1632 public static Delegate GetDelegateForFunctionPointer (IntPtr ptr, Type t)
1635 throw new ArgumentNullException ("t");
1636 if (!t.IsSubclassOf (typeof (MulticastDelegate)) || (t == typeof (MulticastDelegate)))
1637 throw new ArgumentException ("Type is not a delegate", "t");
1638 if (t.IsGenericType)
1639 throw new ArgumentException ("The specified Type must not be a generic type definition.");
1640 if (ptr == IntPtr.Zero)
1641 throw new ArgumentNullException ("ptr");
1643 return GetDelegateForFunctionPointerInternal (ptr, t);
1646 public static TDelegate GetDelegateForFunctionPointer<TDelegate> (IntPtr ptr) {
1647 return (TDelegate) (object) GetDelegateForFunctionPointer (ptr, typeof (TDelegate));
1650 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1651 private static extern IntPtr GetFunctionPointerForDelegateInternal (Delegate d);
1653 public static IntPtr GetFunctionPointerForDelegate (Delegate d)
1656 throw new ArgumentNullException ("d");
1658 return GetFunctionPointerForDelegateInternal (d);
1661 public static IntPtr GetFunctionPointerForDelegate<TDelegate> (TDelegate d) {
1663 throw new ArgumentNullException ("d");
1665 return GetFunctionPointerForDelegateInternal ((Delegate)(object)d);
1668 internal static void SetLastWin32Error (int error)