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 ();
72 public static bool AreComObjectsAvailableForCleanup ()
77 [MethodImplAttribute(MethodImplOptions.InternalCall)]
78 public extern static IntPtr AllocCoTaskMem (int cb);
80 [MethodImplAttribute(MethodImplOptions.InternalCall)]
81 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
82 public extern static IntPtr AllocHGlobal (IntPtr cb);
84 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
85 public static IntPtr AllocHGlobal (int cb)
87 return AllocHGlobal ((IntPtr)cb);
91 public static object BindToMoniker (string monikerName)
93 throw new NotImplementedException ();
97 public static void ChangeWrapperHandleStrength (object otp, bool fIsWeak)
99 throw new NotImplementedException ();
102 [MethodImplAttribute(MethodImplOptions.InternalCall)]
103 internal extern static void copy_to_unmanaged (Array source, int startIndex,
104 IntPtr destination, int length);
106 [MethodImplAttribute(MethodImplOptions.InternalCall)]
107 internal extern static void copy_from_unmanaged (IntPtr source, int startIndex,
108 Array destination, int length);
110 public static void Copy (byte[] source, int startIndex, IntPtr destination, int length)
112 copy_to_unmanaged (source, startIndex, destination, length);
115 public static void Copy (char[] source, int startIndex, IntPtr destination, int length)
117 copy_to_unmanaged (source, startIndex, destination, length);
120 public static void Copy (short[] source, int startIndex, IntPtr destination, int length)
122 copy_to_unmanaged (source, startIndex, destination, length);
125 public static void Copy (int[] source, int startIndex, IntPtr destination, int length)
127 copy_to_unmanaged (source, startIndex, destination, length);
130 public static void Copy (long[] source, int startIndex, IntPtr destination, int length)
132 copy_to_unmanaged (source, startIndex, destination, length);
135 public static void Copy (float[] source, int startIndex, IntPtr destination, int length)
137 copy_to_unmanaged (source, startIndex, destination, length);
140 public static void Copy (double[] source, int startIndex, IntPtr destination, int length)
142 copy_to_unmanaged (source, startIndex, destination, length);
145 public static void Copy (IntPtr[] source, int startIndex, IntPtr destination, int length)
147 copy_to_unmanaged (source, startIndex, destination, length);
150 public static void Copy (IntPtr source, byte[] destination, int startIndex, int length)
152 copy_from_unmanaged (source, startIndex, destination, length);
155 public static void Copy (IntPtr source, char[] destination, int startIndex, int length)
157 copy_from_unmanaged (source, startIndex, destination, length);
160 public static void Copy (IntPtr source, short[] destination, int startIndex, int length)
162 copy_from_unmanaged (source, startIndex, destination, length);
165 public static void Copy (IntPtr source, int[] destination, int startIndex, int length)
167 copy_from_unmanaged (source, startIndex, destination, length);
170 public static void Copy (IntPtr source, long[] destination, int startIndex, int length)
172 copy_from_unmanaged (source, startIndex, destination, length);
175 public static void Copy (IntPtr source, float[] destination, int startIndex, int length)
177 copy_from_unmanaged (source, startIndex, destination, length);
180 public static void Copy (IntPtr source, double[] destination, int startIndex, int length)
182 copy_from_unmanaged (source, startIndex, destination, length);
185 public static void Copy (IntPtr source, IntPtr[] destination, int startIndex, int length)
187 copy_from_unmanaged (source, startIndex, destination, length);
190 public static IntPtr CreateAggregatedObject (IntPtr pOuter,
193 throw new NotImplementedException ();
196 public static IntPtr CreateAggregatedObject<T> (IntPtr pOuter, T o) {
197 return CreateAggregatedObject (pOuter, (object)o);
200 #if !FULL_AOT_RUNTIME
201 public static object CreateWrapperOfType (object o, Type t)
203 __ComObject co = o as __ComObject;
205 throw new ArgumentException ("o must derive from __ComObject", "o");
207 throw new ArgumentNullException ("t");
209 Type[] itfs = o.GetType ().GetInterfaces ();
210 foreach (Type itf in itfs) {
211 if (itf.IsImport && co.GetInterface (itf) == IntPtr.Zero)
212 throw new InvalidCastException ();
215 return ComInteropProxy.GetProxy (co.IUnknown, t).GetTransparentProxy ();
218 public static TWrapper CreateWrapperOfType<T, TWrapper> (T o) {
219 return (TWrapper)CreateWrapperOfType ((object)o, typeof (TWrapper));
223 [MethodImplAttribute(MethodImplOptions.InternalCall)]
225 public extern static void DestroyStructure (IntPtr ptr, Type structuretype);
227 public static void DestroyStructure<T> (IntPtr ptr) {
228 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 (object o, Type T, CustomQueryInterfaceMode mode)
353 throw new NotImplementedException ();
356 public static IntPtr GetComInterfaceForObject<T, TInterface> (T o) {
357 return GetComInterfaceForObject ((object)o, typeof (T));
361 public static IntPtr GetComInterfaceForObjectInContext (object o, Type t)
363 throw new NotImplementedException ();
366 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
367 public static object GetComObjectData (object obj, object key)
369 throw new NotSupportedException ("MSDN states user code should never need to call this method.");
373 [MethodImplAttribute(MethodImplOptions.InternalCall)]
374 private extern static int GetComSlotForMethodInfoInternal (MemberInfo m);
377 public static int GetComSlotForMethodInfo (MemberInfo m)
381 throw new ArgumentNullException ("m");
382 if (!(m is MethodInfo))
383 throw new ArgumentException ("The MemberInfo must be an interface method.", "m");
384 if (!m.DeclaringType.IsInterface)
385 throw new ArgumentException ("The MemberInfo must be an interface method.", "m");
386 return GetComSlotForMethodInfoInternal (m);
388 throw new NotImplementedException ();
393 public static int GetEndComSlot (Type t)
395 throw new NotImplementedException ();
399 public static int GetExceptionCode()
401 throw new NotImplementedException ();
406 public static IntPtr GetExceptionPointers()
408 throw new NotImplementedException ();
411 public static IntPtr GetHINSTANCE (Module m)
414 throw new ArgumentNullException ("m");
416 return m.GetHINSTANCE ();
418 #endif // !FULL_AOT_RUNTIME
420 #if !FULL_AOT_RUNTIME
421 public static int GetHRForException (Exception e)
423 #if FEATURE_COMINTEROP
424 var errorInfo = new ManagedErrorInfo(e);
425 SetErrorInfo (0, errorInfo);
434 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
435 public static int GetHRForLastWin32Error()
437 throw new NotImplementedException ();
440 [MethodImplAttribute (MethodImplOptions.InternalCall)]
441 private extern static IntPtr GetIDispatchForObjectInternal (object o);
443 public static IntPtr GetIDispatchForObject (object o)
445 IntPtr pUnk = GetIDispatchForObjectInternal (o);
446 // Internal method does not AddRef
452 public static IntPtr GetIDispatchForObjectInContext (object o)
454 throw new NotImplementedException ();
458 public static IntPtr GetITypeInfoForType (Type t)
460 throw new NotImplementedException ();
463 [MethodImplAttribute (MethodImplOptions.InternalCall)]
464 private extern static IntPtr GetIUnknownForObjectInternal (object o);
466 public static IntPtr GetIUnknownForObject (object o)
468 IntPtr pUnk = GetIUnknownForObjectInternal (o);
469 // Internal method does not AddRef
475 public static IntPtr GetIUnknownForObjectInContext (object o)
477 throw new NotImplementedException ();
481 [Obsolete ("This method has been deprecated")]
482 public static IntPtr GetManagedThunkForUnmanagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
484 throw new NotImplementedException ();
488 public static MemberInfo GetMethodInfoForComSlot (Type t, int slot, ref ComMemberType memberType)
490 throw new NotImplementedException ();
493 public static void GetNativeVariantForObject (object obj, IntPtr pDstNativeVariant)
495 Variant vt = new Variant();
497 Marshal.StructureToPtr(vt, pDstNativeVariant, false);
500 public static void GetNativeVariantForObject<T> (T obj, IntPtr pDstNativeVariant) {
501 GetNativeVariantForObject ((object)obj, pDstNativeVariant);
505 [MethodImplAttribute (MethodImplOptions.InternalCall)]
506 private static extern object GetObjectForCCW (IntPtr pUnk);
509 public static object GetObjectForIUnknown (IntPtr pUnk)
512 object obj = GetObjectForCCW (pUnk);
515 ComInteropProxy proxy = ComInteropProxy.GetProxy (pUnk, typeof (__ComObject));
516 obj = proxy.GetTransparentProxy ();
520 throw new NotImplementedException ();
524 public static object GetObjectForNativeVariant (IntPtr pSrcNativeVariant)
526 Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
527 return vt.GetValue();
530 public static T GetObjectForNativeVariant<T> (IntPtr pSrcNativeVariant) {
531 Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
532 return (T)vt.GetValue();
535 public static object[] GetObjectsForNativeVariants (IntPtr aSrcNativeVariant, int cVars)
538 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
539 object[] objects = new object[cVars];
540 for (int i = 0; i < cVars; i++)
541 objects[i] = GetObjectForNativeVariant ((IntPtr)(aSrcNativeVariant.ToInt64 () +
542 i * SizeOf (typeof(Variant))));
546 public static T[] GetObjectsForNativeVariants<T> (IntPtr aSrcNativeVariant, int cVars) {
548 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
549 T[] objects = new T[cVars];
550 for (int i = 0; i < cVars; i++)
551 objects[i] = GetObjectForNativeVariant<T> ((IntPtr)(aSrcNativeVariant.ToInt64 () +
552 i * SizeOf (typeof(Variant))));
557 public static int GetStartComSlot (Type t)
559 throw new NotImplementedException ();
563 [Obsolete ("This method has been deprecated")]
564 public static Thread GetThreadFromFiberCookie (int cookie)
566 throw new NotImplementedException ();
569 public static object GetTypedObjectForIUnknown (IntPtr pUnk, Type t)
571 ComInteropProxy proxy = new ComInteropProxy (pUnk, t);
572 __ComObject co = (__ComObject)proxy.GetTransparentProxy ();
573 foreach (Type itf in t.GetInterfaces ()) {
574 if ((itf.Attributes & TypeAttributes.Import) == TypeAttributes.Import) {
575 if (co.GetInterface (itf) == IntPtr.Zero)
583 public static Type GetTypeForITypeInfo (IntPtr piTypeInfo)
585 throw new NotImplementedException ();
588 public static Type GetTypeFromCLSID (Guid clsid)
590 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);
700 public static IntPtr OffsetOf<T> (string fieldName) {
701 return OffsetOf (typeof (T), fieldName);
704 [MethodImplAttribute(MethodImplOptions.InternalCall)]
705 public extern static void Prelink (MethodInfo m);
707 [MethodImplAttribute(MethodImplOptions.InternalCall)]
708 public extern static void PrelinkAll (Type c);
710 [MethodImplAttribute(MethodImplOptions.InternalCall)]
711 public extern static string PtrToStringAnsi (IntPtr ptr);
713 [MethodImplAttribute(MethodImplOptions.InternalCall)]
714 public extern static string PtrToStringAnsi (IntPtr ptr, int len);
716 public static string PtrToStringAuto (IntPtr ptr)
718 return SystemDefaultCharSize == 2
719 ? PtrToStringUni (ptr) : PtrToStringAnsi (ptr);
722 public static string PtrToStringAuto (IntPtr ptr, int len)
724 return SystemDefaultCharSize == 2
725 ? PtrToStringUni (ptr, len) : PtrToStringAnsi (ptr, len);
728 [MethodImplAttribute(MethodImplOptions.InternalCall)]
729 public extern static string PtrToStringUni (IntPtr ptr);
731 [MethodImplAttribute(MethodImplOptions.InternalCall)]
732 public extern static string PtrToStringUni (IntPtr ptr, int len);
735 [MethodImplAttribute(MethodImplOptions.InternalCall)]
736 public extern static string PtrToStringBSTR (IntPtr ptr);
738 public static string PtrToStringBSTR (IntPtr ptr)
740 throw new NotImplementedException ();
744 [MethodImplAttribute(MethodImplOptions.InternalCall)]
746 public extern static void PtrToStructure (IntPtr ptr, object structure);
748 [MethodImplAttribute(MethodImplOptions.InternalCall)]
750 public extern static object PtrToStructure (IntPtr ptr, Type structureType);
752 public static void PtrToStructure<T> (IntPtr ptr, T structure) {
753 PtrToStructure (ptr, (object)structure);
756 public static T PtrToStructure<T> (IntPtr ptr) {
757 return (T) PtrToStructure (ptr, typeof (T));
761 [MethodImplAttribute (MethodImplOptions.InternalCall)]
762 private extern static int QueryInterfaceInternal (IntPtr pUnk, ref Guid iid, out IntPtr ppv);
765 public static int QueryInterface (IntPtr pUnk, ref Guid iid, out IntPtr ppv)
768 if (pUnk == IntPtr.Zero)
769 throw new ArgumentException ("Value cannot be null.", "pUnk");
770 return QueryInterfaceInternal (pUnk, ref iid, out ppv);
772 throw new NotImplementedException ();
776 public static byte ReadByte (IntPtr ptr)
783 public static byte ReadByte (IntPtr ptr, int ofs) {
785 return *((byte*)ptr + ofs);
790 [SuppressUnmanagedCodeSecurity]
791 public static byte ReadByte ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
793 throw new NotImplementedException ();
796 public unsafe static short ReadInt16 (IntPtr ptr)
798 byte *addr = (byte *) ptr;
800 // The mono JIT can't inline this due to the hight number of calls
801 // return ReadInt16 (ptr, 0);
803 if (((uint)addr & 1) == 0)
804 return *(short*)addr;
807 Buffer.Memcpy ((byte*)&s, (byte*)ptr, 2);
811 public unsafe static short ReadInt16 (IntPtr ptr, int ofs)
813 byte *addr = ((byte *) ptr) + ofs;
815 if (((uint) addr & 1) == 0)
816 return *(short*)addr;
819 Buffer.Memcpy ((byte*)&s, addr, 2);
824 [SuppressUnmanagedCodeSecurity]
825 public static short ReadInt16 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
827 throw new NotImplementedException ();
830 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
831 public unsafe static int ReadInt32 (IntPtr ptr)
833 byte *addr = (byte *) ptr;
835 if (((uint)addr & 3) == 0)
839 Buffer.Memcpy ((byte*)&s, addr, 4);
843 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
844 public unsafe static int ReadInt32 (IntPtr ptr, int ofs)
846 byte *addr = ((byte *) ptr) + ofs;
848 if ((((int) addr) & 3) == 0)
852 Buffer.Memcpy ((byte*)&s, addr, 4);
857 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
859 [SuppressUnmanagedCodeSecurity]
860 public static int ReadInt32 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
862 throw new NotImplementedException ();
865 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
866 public unsafe static long ReadInt64 (IntPtr ptr)
868 byte *addr = (byte *) ptr;
870 // The real alignment might be 4 on some platforms, but this is just an optimization,
871 // so it doesn't matter.
872 if (((uint) addr & 7) == 0)
876 Buffer.Memcpy ((byte*)&s, addr, 8);
880 public unsafe static long ReadInt64 (IntPtr ptr, int ofs)
882 byte *addr = ((byte *) ptr) + ofs;
884 if (((uint) addr & 7) == 0)
888 Buffer.Memcpy ((byte*)&s, addr, 8);
892 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
894 [SuppressUnmanagedCodeSecurity]
895 public static long ReadInt64 ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
897 throw new NotImplementedException ();
900 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
901 public static IntPtr ReadIntPtr (IntPtr ptr)
903 if (IntPtr.Size == 4)
904 return (IntPtr)ReadInt32 (ptr);
906 return (IntPtr)ReadInt64 (ptr);
909 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
910 public static IntPtr ReadIntPtr (IntPtr ptr, int ofs)
912 if (IntPtr.Size == 4)
913 return (IntPtr)ReadInt32 (ptr, ofs);
915 return (IntPtr)ReadInt64 (ptr, ofs);
918 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
920 public static IntPtr ReadIntPtr ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
922 throw new NotImplementedException ();
925 [MethodImplAttribute (MethodImplOptions.InternalCall)]
926 public extern static IntPtr ReAllocCoTaskMem (IntPtr pv, int cb);
928 [MethodImplAttribute(MethodImplOptions.InternalCall)]
929 public extern static IntPtr ReAllocHGlobal (IntPtr pv, IntPtr cb);
932 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
933 [MethodImplAttribute (MethodImplOptions.InternalCall)]
934 private extern static int ReleaseInternal (IntPtr pUnk);
937 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
938 public static int Release (IntPtr pUnk)
941 if (pUnk == IntPtr.Zero)
942 throw new ArgumentException ("Value cannot be null.", "pUnk");
944 return ReleaseInternal (pUnk);
946 throw new NotImplementedException ();
950 #if !FULL_AOT_RUNTIME
951 [MethodImplAttribute (MethodImplOptions.InternalCall)]
952 private extern static int ReleaseComObjectInternal (object co);
954 public static int ReleaseComObject (object o)
957 throw new ArgumentException ("Value cannot be null.", "o");
958 if (!IsComObject (o))
959 throw new ArgumentException ("Value must be a Com object.", "o");
960 return ReleaseComObjectInternal (o);
965 public static void ReleaseThreadCache()
967 throw new NotImplementedException ();
970 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
971 public static bool SetComObjectData (object obj, object key, object data)
973 throw new NotSupportedException ("MSDN states user code should never need to call this method.");
978 public static int SizeOf (object structure)
980 return SizeOf (structure.GetType ());
983 [MethodImplAttribute(MethodImplOptions.InternalCall)]
984 public extern static int SizeOf (Type t);
986 public static int SizeOf<T> () {
987 return SizeOf (typeof (T));
990 public static int SizeOf<T> (T structure) {
991 return SizeOf (structure.GetType ());
994 internal static uint SizeOfType (Type type)
996 return (uint) SizeOf (type);
999 internal static uint AlignedSizeOf<T> () where T : struct
1001 uint size = SizeOfType (typeof (T));
1002 if (size == 1 || size == 2)
1004 if (IntPtr.Size == 8 && size == 4)
1006 return (size + 3) & (~((uint)3));
1009 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1010 public extern static IntPtr StringToBSTR (string s);
1013 // I believe this is wrong, because in Mono and in P/Invoke
1014 // we treat "Ansi" conversions as UTF-8 conversions, while
1015 // this one does not do this
1017 public static IntPtr StringToCoTaskMemAnsi (string s)
1019 int length = s.Length + 1;
1020 IntPtr ctm = AllocCoTaskMem (length);
1022 byte[] asBytes = new byte[length];
1023 for (int i = 0; i < s.Length; i++)
1024 asBytes[i] = (byte)s[i];
1025 asBytes[s.Length] = 0;
1027 copy_to_unmanaged (asBytes, 0, ctm, length);
1031 public static IntPtr StringToCoTaskMemAuto (string s)
1033 return SystemDefaultCharSize == 2
1034 ? StringToCoTaskMemUni (s) : StringToCoTaskMemAnsi (s);
1037 public static IntPtr StringToCoTaskMemUni (string s)
1039 int length = s.Length + 1;
1040 IntPtr ctm = AllocCoTaskMem (length * 2);
1042 char[] asChars = new char[length];
1043 s.CopyTo (0, asChars, 0, s.Length);
1044 asChars[s.Length] = '\0';
1046 copy_to_unmanaged (asChars, 0, ctm, length);
1050 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1051 public extern static IntPtr StringToHGlobalAnsi (string s);
1053 public static IntPtr StringToHGlobalAuto (string s)
1055 return SystemDefaultCharSize == 2
1056 ? StringToHGlobalUni (s) : StringToHGlobalAnsi (s);
1059 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1060 public extern static IntPtr StringToHGlobalUni (string s);
1062 public static IntPtr SecureStringToBSTR (SecureString s)
1065 throw new ArgumentNullException ("s");
1067 byte[] buffer = s.GetBuffer ();
1070 // SecureString doesn't take endian-ness into account.
1071 // Therefore swap bytes here before we send it to c-side if little-endian.
1072 if (BitConverter.IsLittleEndian) {
1073 for (int i = 0; i < buffer.Length; i += 2) {
1075 buffer[i] = buffer[i + 1];
1079 return BufferToBSTR (buffer, len);
1082 public static IntPtr SecureStringToCoTaskMemAnsi (SecureString s)
1085 throw new ArgumentNullException ("s");
1087 IntPtr ctm = AllocCoTaskMem (len + 1);
1088 byte [] copy = new byte [len+1];
1091 byte [] buffer = s.GetBuffer ();
1093 for (; i < len; i++, j += 2){
1094 copy [i] = buffer [j+1];
1099 copy_to_unmanaged (copy, 0, ctm, len+1);
1101 // Ensure that we clear the buffer.
1102 for (int i = len; i > 0; ){
1110 public static IntPtr SecureStringToCoTaskMemUnicode (SecureString s)
1113 throw new ArgumentNullException ("s");
1115 IntPtr ctm = AllocCoTaskMem (len * 2 + 2);
1116 byte [] buffer = null;
1118 buffer = s.GetBuffer ();
1119 for (int i = 0; i < len; i++)
1120 WriteInt16 (ctm, i * 2, (short) ((buffer [(i*2)] << 8) | (buffer [i*2+1])));
1121 WriteInt16 (ctm, buffer.Length, 0);
1124 for (int i = buffer.Length; i > 0; ){
1132 public static IntPtr SecureStringToGlobalAllocAnsi (SecureString s)
1135 throw new ArgumentNullException ("s");
1136 return SecureStringToCoTaskMemAnsi (s);
1139 public static IntPtr SecureStringToGlobalAllocUnicode (SecureString s)
1142 throw new ArgumentNullException ("s");
1143 return SecureStringToCoTaskMemUnicode (s);
1146 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
1148 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1149 public extern static void StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld);
1151 public static void StructureToPtr<T> (T structure, IntPtr ptr, bool fDeleteOld) {
1152 StructureToPtr ((object)structure, ptr, fDeleteOld);
1155 public static void ThrowExceptionForHR (int errorCode) {
1156 Exception ex = GetExceptionForHR (errorCode);
1161 public static void ThrowExceptionForHR (int errorCode, IntPtr errorInfo) {
1162 Exception ex = GetExceptionForHR (errorCode, errorInfo);
1168 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1169 public extern static IntPtr BufferToBSTR (Array ptr, int slen);
1171 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1172 public extern static IntPtr UnsafeAddrOfPinnedArrayElement (Array arr, int index);
1174 public static IntPtr UnsafeAddrOfPinnedArrayElement<T> (T[] arr, int index) {
1175 return UnsafeAddrOfPinnedArrayElement ((Array)arr, index);
1178 public static void WriteByte (IntPtr ptr, byte val)
1185 public static void WriteByte (IntPtr ptr, int ofs, byte val) {
1187 *(byte*)(IntPtr.Add (ptr, ofs)) = val;
1192 [SuppressUnmanagedCodeSecurity]
1193 public static void WriteByte ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, byte val)
1195 throw new NotImplementedException ();
1198 public static unsafe void WriteInt16 (IntPtr ptr, short val)
1200 byte *addr = (byte *) ptr;
1202 if (((uint)addr & 1) == 0)
1203 *(short*)addr = val;
1205 Buffer.Memcpy (addr, (byte*)&val, 2);
1208 public static unsafe void WriteInt16 (IntPtr ptr, int ofs, short val)
1210 byte *addr = ((byte *) ptr) + ofs;
1212 if (((uint)addr & 1) == 0)
1213 *(short*)addr = val;
1215 Buffer.Memcpy (addr, (byte*)&val, 2);
1220 [SuppressUnmanagedCodeSecurity]
1221 public static void WriteInt16 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, short val)
1223 throw new NotImplementedException ();
1226 public static void WriteInt16 (IntPtr ptr, char val)
1228 WriteInt16 (ptr, 0, (short)val);
1231 public static void WriteInt16 (IntPtr ptr, int ofs, char val)
1233 WriteInt16 (ptr, ofs, (short)val);
1237 public static void WriteInt16([In, Out] object ptr, int ofs, char val)
1239 throw new NotImplementedException ();
1242 public static unsafe void WriteInt32 (IntPtr ptr, int val)
1244 byte *addr = (byte *) ptr;
1246 if (((uint)addr & 3) == 0)
1249 Buffer.Memcpy (addr, (byte*)&val, 4);
1253 public unsafe static void WriteInt32 (IntPtr ptr, int ofs, int val)
1255 byte *addr = ((byte *) ptr) + ofs;
1257 if (((uint)addr & 3) == 0)
1260 Buffer.Memcpy (addr, (byte*)&val, 4);
1265 [SuppressUnmanagedCodeSecurity]
1266 public static void WriteInt32([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, int val)
1268 throw new NotImplementedException ();
1271 public static unsafe void WriteInt64 (IntPtr ptr, long val)
1273 byte *addr = (byte *) ptr;
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);
1283 public static unsafe void WriteInt64 (IntPtr ptr, int ofs, long val)
1285 byte *addr = ((byte *) ptr) + ofs;
1287 // The real alignment might be 4 on some platforms, but this is just an optimization,
1288 // so it doesn't matter.
1289 if (((uint)addr & 7) == 0)
1292 Buffer.Memcpy (addr, (byte*)&val, 8);
1296 [SuppressUnmanagedCodeSecurity]
1297 public static void WriteInt64 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, long val)
1299 throw new NotImplementedException ();
1302 public static void WriteIntPtr (IntPtr ptr, IntPtr val)
1304 if (IntPtr.Size == 4)
1305 WriteInt32 (ptr, (int)val);
1307 WriteInt64 (ptr, (long)val);
1310 public static void WriteIntPtr (IntPtr ptr, int ofs, IntPtr val)
1312 if (IntPtr.Size == 4)
1313 WriteInt32 (ptr, ofs, (int)val);
1315 WriteInt64 (ptr, ofs, (long)val);
1319 public static void WriteIntPtr([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, IntPtr val)
1321 throw new NotImplementedException ();
1324 private static Exception ConvertHrToException (int errorCode)
1326 const int MSEE_E_APPDOMAINUNLOADED = unchecked ((int)0x80131014L);
1327 const int COR_E_APPLICATION = unchecked ((int)0x80131600L);
1328 const int E_INVALIDARG = unchecked ((int)0x80070057);
1329 const int COR_E_ARGUMENTOUTOFRANGE = unchecked ((int)0x80131502L);
1330 const int COR_E_ARITHMETIC = unchecked ((int)0x80070216);
1331 const int COR_E_ARRAYTYPEMISMATCH = unchecked ((int)0x80131503L);
1332 const int COR_E_BADIMAGEFORMAT = unchecked ((int)0x8007000BL);
1333 const int ERROR_BAD_FORMAT = unchecked ((int)0x0B);
1334 //const int COR_E_COMEMULATE_ERROR = unchecked ((int)?);
1335 const int COR_E_CONTEXTMARSHAL = unchecked ((int)0x80131504L);
1336 //const int COR_E_CORE = unchecked ((int)?);
1337 const int NTE_FAIL = unchecked ((int)0x80090020L);
1338 const int COR_E_DIRECTORYNOTFOUND = unchecked ((int)0x80070003L);
1339 const int ERROR_PATH_NOT_FOUND = unchecked ((int)0x03);
1340 const int COR_E_DIVIDEBYZERO = unchecked ((int)0x80020012L);
1341 const int COR_E_DUPLICATEWAITOBJECT = unchecked ((int)0x80131529L);
1342 const int COR_E_ENDOFSTREAM = unchecked ((int)0x80070026L);
1343 const int COR_E_TYPELOAD = unchecked ((int)0x80131522L);
1344 const int COR_E_EXCEPTION = unchecked ((int)0x80131500L);
1345 const int COR_E_EXECUTIONENGINE = unchecked ((int)0x80131506L);
1346 const int COR_E_FIELDACCESS = unchecked ((int)0x80131507L);
1347 const int COR_E_FILENOTFOUND = unchecked ((int)0x80070002L);
1348 const int ERROR_FILE_NOT_FOUND = unchecked ((int)0x02);
1349 const int COR_E_FORMAT = unchecked ((int)0x80131537L);
1350 const int COR_E_INDEXOUTOFRANGE = unchecked ((int)0x80131508L);
1351 const int COR_E_INVALIDCAST = unchecked ((int)0x80004002L);
1352 const int COR_E_INVALIDCOMOBJECT = unchecked ((int)0x80131527L);
1353 const int COR_E_INVALIDFILTERCRITERIA = unchecked ((int)0x80131601L);
1354 const int COR_E_INVALIDOLEVARIANTTYPE = unchecked ((int)0x80131531L);
1355 const int COR_E_INVALIDOPERATION = unchecked ((int)0x80131509L);
1356 const int COR_E_IO = unchecked ((int)0x80131620L);
1357 const int COR_E_MEMBERACCESS = unchecked ((int)0x8013151AL);
1358 const int COR_E_METHODACCESS = unchecked ((int)0x80131510L);
1359 const int COR_E_MISSINGFIELD = unchecked ((int)0x80131511L);
1360 const int COR_E_MISSINGMANIFESTRESOURCE = unchecked ((int)0x80131532L);
1361 const int COR_E_MISSINGMEMBER = unchecked ((int)0x80131512L);
1362 const int COR_E_MISSINGMETHOD = unchecked ((int)0x80131513L);
1363 const int COR_E_MULTICASTNOTSUPPORTED = unchecked ((int)0x80131514L);
1364 const int COR_E_NOTFINITENUMBER = unchecked ((int)0x80131528L);
1365 const int E_NOTIMPL = unchecked ((int)0x80004001L);
1366 const int COR_E_NOTSUPPORTED = unchecked ((int)0x80131515L);
1367 const int COR_E_NULLREFERENCE = unchecked ((int)0x80004003L);
1368 const int E_OUTOFMEMORY = unchecked ((int)0x8007000EL);
1369 const int COR_E_OVERFLOW = unchecked ((int)0x80131516L);
1370 const int COR_E_PATHTOOLONG = unchecked ((int)0x800700CEL);
1371 const int ERROR_FILENAME_EXCED_RANGE = unchecked ((int)0xCE);
1372 const int COR_E_RANK = unchecked ((int)0x80131517L);
1373 const int COR_E_REFLECTIONTYPELOAD = unchecked ((int)0x80131602L);
1374 const int COR_E_REMOTING = unchecked ((int)0x8013150BL);
1375 const int COR_E_SAFEARRAYTYPEMISMATCH = unchecked ((int)0x80131533L);
1376 const int COR_E_SECURITY = unchecked ((int)0x8013150AL);
1377 const int COR_E_SERIALIZATION = unchecked ((int)0x8013150CL);
1378 const int COR_E_STACKOVERFLOW = unchecked ((int)0x800703E9L);
1379 const int ERROR_STACK_OVERFLOW = unchecked ((int)0x03E9);
1380 const int COR_E_SYNCHRONIZATIONLOCK = unchecked ((int)0x80131518L);
1381 const int COR_E_SYSTEM = unchecked ((int)0x80131501L);
1382 const int COR_E_TARGET = unchecked ((int)0x80131603L);
1383 const int COR_E_TARGETINVOCATION = unchecked ((int)0x80131604L);
1384 const int COR_E_TARGETPARAMCOUNT = unchecked ((int)0x8002000EL);
1385 const int COR_E_THREADABORTED = unchecked ((int)0x80131530L);
1386 const int COR_E_THREADINTERRUPTED = unchecked ((int)0x80131519L);
1387 const int COR_E_THREADSTATE = unchecked ((int)0x80131520L);
1388 const int COR_E_THREADSTOP = unchecked ((int)0x80131521L);
1389 const int COR_E_TYPEINITIALIZATION = unchecked ((int)0x80131534L);
1390 const int COR_E_VERIFICATION = unchecked ((int)0x8013150DL);
1391 //const int COR_E_WEAKREFERENCE = unchecked ((int)?);
1392 //const int COR_E_VTABLECALLSNOTSUPPORTED = unchecked ((int));
1394 switch (errorCode) {
1395 case MSEE_E_APPDOMAINUNLOADED:
1396 return new AppDomainUnloadedException ();
1397 case COR_E_APPLICATION:
1398 return new ApplicationException ();
1400 return new ArgumentException ();
1401 case COR_E_ARGUMENTOUTOFRANGE:
1402 return new ArgumentOutOfRangeException ();
1403 case COR_E_ARITHMETIC:
1404 return new ArithmeticException ();
1405 case COR_E_ARRAYTYPEMISMATCH:
1406 return new ArrayTypeMismatchException ();
1407 case COR_E_BADIMAGEFORMAT:
1408 case ERROR_BAD_FORMAT:
1409 return new BadImageFormatException ();
1410 // case COR_E_COMEMULATE_ERROR:
1411 // return new COMEmulateException ();
1412 case COR_E_CONTEXTMARSHAL:
1413 return new ContextMarshalException ();
1415 // return new CoreException ();
1417 return new System.Security.Cryptography.CryptographicException ();
1418 case COR_E_DIRECTORYNOTFOUND:
1419 case ERROR_PATH_NOT_FOUND:
1420 return new System.IO.DirectoryNotFoundException ();
1421 case COR_E_DIVIDEBYZERO:
1422 return new DivideByZeroException ();
1423 case COR_E_DUPLICATEWAITOBJECT:
1424 return new DuplicateWaitObjectException ();
1425 case COR_E_ENDOFSTREAM:
1426 return new System.IO.EndOfStreamException ();
1427 case COR_E_EXCEPTION:
1428 return new Exception ();
1429 case COR_E_EXECUTIONENGINE:
1430 return new ExecutionEngineException ();
1431 case COR_E_FIELDACCESS:
1432 return new FieldAccessException ();
1433 case COR_E_FILENOTFOUND:
1434 case ERROR_FILE_NOT_FOUND:
1435 return new System.IO.FileNotFoundException ();
1437 return new FormatException ();
1438 case COR_E_INDEXOUTOFRANGE:
1439 return new IndexOutOfRangeException ();
1440 case COR_E_INVALIDCAST:
1441 // E_NOINTERFACE has same value as COR_E_INVALIDCAST
1442 return new InvalidCastException ();
1443 case COR_E_INVALIDCOMOBJECT:
1444 return new InvalidComObjectException ();
1445 case COR_E_INVALIDFILTERCRITERIA:
1446 return new InvalidFilterCriteriaException ();
1447 case COR_E_INVALIDOLEVARIANTTYPE:
1448 return new InvalidOleVariantTypeException ();
1449 case COR_E_INVALIDOPERATION:
1450 return new InvalidOperationException ();
1452 return new System.IO.IOException ();
1453 case COR_E_MEMBERACCESS:
1454 return new MemberAccessException ();
1455 case COR_E_METHODACCESS:
1456 return new MethodAccessException ();
1457 case COR_E_MISSINGFIELD:
1458 return new MissingFieldException ();
1459 case COR_E_MISSINGMANIFESTRESOURCE:
1460 return new System.Resources.MissingManifestResourceException ();
1461 case COR_E_MISSINGMEMBER:
1462 return new MissingMemberException ();
1463 case COR_E_MISSINGMETHOD:
1464 return new MissingMethodException ();
1465 case COR_E_MULTICASTNOTSUPPORTED:
1466 return new MulticastNotSupportedException ();
1467 case COR_E_NOTFINITENUMBER:
1468 return new NotFiniteNumberException ();
1470 return new NotImplementedException ();
1471 case COR_E_NOTSUPPORTED:
1472 return new NotSupportedException ();
1473 case COR_E_NULLREFERENCE:
1474 // E_POINTER has the same value as COR_E_NULLREFERENCE
1475 return new NullReferenceException ();
1477 // COR_E_OUTOFMEMORY has the same value as E_OUTOFMEMORY
1478 return new OutOfMemoryException ();
1479 case COR_E_OVERFLOW:
1480 return new OverflowException ();
1481 case COR_E_PATHTOOLONG:
1482 case ERROR_FILENAME_EXCED_RANGE:
1483 return new System.IO.PathTooLongException ();
1485 return new RankException ();
1486 case COR_E_REFLECTIONTYPELOAD:
1487 return new System.Reflection.ReflectionTypeLoadException (new Type[] { }, new Exception[] { });
1488 case COR_E_REMOTING:
1489 return new System.Runtime.Remoting.RemotingException ();
1490 case COR_E_SAFEARRAYTYPEMISMATCH:
1491 return new SafeArrayTypeMismatchException ();
1492 case COR_E_SECURITY:
1493 return new SecurityException ();
1494 case COR_E_SERIALIZATION:
1495 return new System.Runtime.Serialization.SerializationException ();
1496 case COR_E_STACKOVERFLOW:
1497 case ERROR_STACK_OVERFLOW:
1498 return new StackOverflowException ();
1499 case COR_E_SYNCHRONIZATIONLOCK:
1500 return new SynchronizationLockException ();
1502 return new SystemException ();
1504 return new TargetException ();
1505 case COR_E_TARGETINVOCATION:
1506 return new System.Reflection.TargetInvocationException (null);
1507 case COR_E_TARGETPARAMCOUNT:
1508 return new TargetParameterCountException ();
1509 // case COR_E_THREADABORTED:
1510 // ThreadAbortException c'tor is inaccessible
1511 // return new System.Threading.ThreadAbortException ();
1512 case COR_E_THREADINTERRUPTED:
1513 return new ThreadInterruptedException ();
1514 case COR_E_THREADSTATE:
1515 return new ThreadStateException ();
1516 // case COR_E_THREADSTOP:
1517 // ThreadStopException does not exist
1518 // return new System.Threading.ThreadStopException ();
1519 case COR_E_TYPELOAD:
1520 return new TypeLoadException ();
1521 // MSDN lists COR_E_TYPELOAD twice with different exceptions.
1522 // return new EntryPointNotFoundException ();
1523 case COR_E_TYPEINITIALIZATION:
1524 return new TypeInitializationException("", null);
1525 case COR_E_VERIFICATION:
1526 return new VerificationException ();
1527 // case COR_E_WEAKREFERENCE:
1528 // return new WeakReferenceException ();
1529 // case COR_E_VTABLECALLSNOTSUPPORTED:
1530 // return new VTableCallsNotSupportedException ();
1533 return new COMException ("", errorCode);
1537 #if FEATURE_COMINTEROP
1538 [DllImport ("oleaut32.dll", CharSet=CharSet.Unicode, EntryPoint = "SetErrorInfo")]
1539 static extern int _SetErrorInfo (int dwReserved,
1540 [MarshalAs(UnmanagedType.Interface)] IErrorInfo pIErrorInfo);
1542 [DllImport ("oleaut32.dll", CharSet=CharSet.Unicode, EntryPoint = "GetErrorInfo")]
1543 static extern int _GetErrorInfo (int dwReserved,
1544 [MarshalAs(UnmanagedType.Interface)] out IErrorInfo ppIErrorInfo);
1546 static bool SetErrorInfoNotAvailable;
1547 static bool GetErrorInfoNotAvailable;
1549 internal static int SetErrorInfo (int dwReserved, IErrorInfo errorInfo)
1554 if (SetErrorInfoNotAvailable)
1558 retVal = _SetErrorInfo (dwReserved, errorInfo);
1561 // ignore any exception - probably there's no suitable SetErrorInfo
1562 // method available.
1563 SetErrorInfoNotAvailable = true;
1568 internal static int GetErrorInfo (int dwReserved, out IErrorInfo errorInfo)
1573 if (GetErrorInfoNotAvailable)
1577 retVal = _GetErrorInfo (dwReserved, out errorInfo);
1580 // ignore any exception - probably there's no suitable GetErrorInfo
1581 // method available.
1582 GetErrorInfoNotAvailable = true;
1587 public static Exception GetExceptionForHR (int errorCode)
1589 return GetExceptionForHR (errorCode, IntPtr.Zero);
1592 public static Exception GetExceptionForHR (int errorCode, IntPtr errorInfo)
1594 #if FEATURE_COMINTEROP
1595 IErrorInfo info = null;
1596 if (errorInfo != (IntPtr)(-1)) {
1597 if (errorInfo == IntPtr.Zero) {
1598 if (GetErrorInfo (0, out info) != 0) {
1602 info = Marshal.GetObjectForIUnknown (errorInfo) as IErrorInfo;
1606 if (info is ManagedErrorInfo && ((ManagedErrorInfo) info).Exception._HResult == errorCode) {
1607 return ((ManagedErrorInfo) info).Exception;
1610 Exception e = ConvertHrToException (errorCode);
1611 if (info != null && e != null) {
1613 info.GetHelpContext (out helpContext);
1615 info.GetSource (out str);
1617 info.GetDescription (out str);
1619 info.GetHelpFile (out str);
1621 if (helpContext == 0) {
1624 e.HelpLink = string.Format ("{0}#{1}", str, helpContext);
1629 return ConvertHrToException (errorCode);
1633 #if !FULL_AOT_RUNTIME
1634 public static int FinalReleaseComObject (object o)
1636 while (ReleaseComObject (o) != 0);
1641 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1642 private static extern Delegate GetDelegateForFunctionPointerInternal (IntPtr ptr, Type t);
1644 public static Delegate GetDelegateForFunctionPointer (IntPtr ptr, Type t)
1647 throw new ArgumentNullException ("t");
1648 if (!t.IsSubclassOf (typeof (MulticastDelegate)) || (t == typeof (MulticastDelegate)))
1649 throw new ArgumentException ("Type is not a delegate", "t");
1650 if (t.IsGenericType)
1651 throw new ArgumentException ("The specified Type must not be a generic type definition.");
1652 if (ptr == IntPtr.Zero)
1653 throw new ArgumentNullException ("ptr");
1655 return GetDelegateForFunctionPointerInternal (ptr, t);
1658 public static TDelegate GetDelegateForFunctionPointer<TDelegate> (IntPtr ptr) {
1659 return (TDelegate) (object) GetDelegateForFunctionPointer (ptr, typeof (TDelegate));
1662 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1663 private static extern IntPtr GetFunctionPointerForDelegateInternal (Delegate d);
1665 public static IntPtr GetFunctionPointerForDelegate (Delegate d)
1668 throw new ArgumentNullException ("d");
1670 return GetFunctionPointerForDelegateInternal (d);
1673 public static IntPtr GetFunctionPointerForDelegate<TDelegate> (TDelegate d) {
1675 throw new ArgumentNullException ("d");
1677 return GetFunctionPointerForDelegateInternal ((Delegate)(object)d);
1680 internal static void SetLastWin32Error (int error)