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;
40 using System.Runtime.InteropServices.ComTypes;
42 using System.Runtime.ConstrainedExecution;
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 public static object CreateWrapperOfType (object o, Type t)
203 throw new PlatformNotSupportedException ();
205 __ComObject co = o as __ComObject;
207 throw new ArgumentException ("o must derive from __ComObject", "o");
209 throw new ArgumentNullException ("t");
211 Type[] itfs = o.GetType ().GetInterfaces ();
212 foreach (Type itf in itfs) {
213 if (itf.IsImport && co.GetInterface (itf) == IntPtr.Zero)
214 throw new InvalidCastException ();
217 return ComInteropProxy.GetProxy (co.IUnknown, t).GetTransparentProxy ();
221 public static TWrapper CreateWrapperOfType<T, TWrapper> (T o) {
222 return (TWrapper)CreateWrapperOfType ((object)o, typeof (TWrapper));
225 [MethodImplAttribute(MethodImplOptions.InternalCall)]
227 public extern static void DestroyStructure (IntPtr ptr, Type structuretype);
229 public static void DestroyStructure<T> (IntPtr ptr) {
230 DestroyStructure (ptr, typeof (T));
233 [MethodImplAttribute(MethodImplOptions.InternalCall)]
234 public extern static void FreeBSTR (IntPtr ptr);
236 [MethodImplAttribute(MethodImplOptions.InternalCall)]
237 public extern static void FreeCoTaskMem (IntPtr ptr);
239 [MethodImplAttribute(MethodImplOptions.InternalCall)]
240 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
241 public extern static void FreeHGlobal (IntPtr hglobal);
243 static void ClearBSTR (IntPtr ptr)
245 int len = ReadInt32 (ptr, -4);
247 for (int i = 0; i < len; i++)
248 WriteByte (ptr, i, 0);
251 public static void ZeroFreeBSTR (IntPtr s)
257 static void ClearAnsi (IntPtr ptr)
259 for (int i = 0; ReadByte (ptr, i) != 0; i++)
260 WriteByte (ptr, i, 0);
263 static void ClearUnicode (IntPtr ptr)
265 for (int i = 0; ReadInt16 (ptr, i) != 0; i += 2)
266 WriteInt16 (ptr, i, 0);
269 public static void ZeroFreeCoTaskMemAnsi (IntPtr s)
275 public static void ZeroFreeCoTaskMemUnicode (IntPtr s)
281 public static void ZeroFreeGlobalAllocAnsi (IntPtr s)
287 public static void ZeroFreeGlobalAllocUnicode (IntPtr s)
293 #if !FULL_AOT_RUNTIME
294 public static Guid GenerateGuidForType (Type type)
299 public static string GenerateProgIdForType (Type type)
301 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (type);
303 foreach (var a in attrs)
305 var dt = a.Constructor.DeclaringType;
306 string name = dt.Name;
307 if (name == "ProgIdAttribute")
309 var args = a.ConstructorArguments;
310 string text = a.ConstructorArguments[0].Value as string;
319 return type.FullName;
323 public static object GetActiveObject (string progID)
325 throw new NotImplementedException ();
329 [MethodImplAttribute (MethodImplOptions.InternalCall)]
330 private extern static IntPtr GetCCW (object o, Type T);
332 private static IntPtr GetComInterfaceForObjectInternal (object o, Type T)
335 return ((__ComObject)o).GetInterface (T);
337 return GetCCW (o, T);
340 #endif // !FULL_AOT_RUNTIME
342 public static IntPtr GetComInterfaceForObject (object o, Type T)
345 throw new PlatformNotSupportedException ();
347 IntPtr pItf = GetComInterfaceForObjectInternal (o, T);
354 public static IntPtr GetComInterfaceForObject (object o, Type T, CustomQueryInterfaceMode mode)
356 throw new NotImplementedException ();
359 public static IntPtr GetComInterfaceForObject<T, TInterface> (T o) {
360 return GetComInterfaceForObject ((object)o, typeof (T));
363 #if !FULL_AOT_RUNTIME
365 public static IntPtr GetComInterfaceForObjectInContext (object o, Type t)
367 throw new NotImplementedException ();
370 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
371 public static object GetComObjectData (object obj, object key)
373 throw new NotSupportedException ("MSDN states user code should never need to call this method.");
377 [MethodImplAttribute(MethodImplOptions.InternalCall)]
378 private extern static int GetComSlotForMethodInfoInternal (MemberInfo m);
381 public static int GetComSlotForMethodInfo (MemberInfo m)
385 throw new ArgumentNullException ("m");
386 if (!(m is MethodInfo))
387 throw new ArgumentException ("The MemberInfo must be an interface method.", "m");
388 if (!m.DeclaringType.IsInterface)
389 throw new ArgumentException ("The MemberInfo must be an interface method.", "m");
390 return GetComSlotForMethodInfoInternal (m);
392 throw new NotImplementedException ();
397 public static int GetEndComSlot (Type t)
399 throw new NotImplementedException ();
404 public static IntPtr GetExceptionPointers()
406 throw new NotImplementedException ();
409 public static IntPtr GetHINSTANCE (Module m)
412 throw new ArgumentNullException ("m");
414 return m.GetHINSTANCE ();
416 #endif // !FULL_AOT_RUNTIME
418 public static int GetExceptionCode ()
420 throw new PlatformNotSupportedException ();
423 public static int GetHRForException (Exception e)
425 if (e == null) return 0;
427 #if FEATURE_COMINTEROP
428 var errorInfo = new ManagedErrorInfo(e);
429 SetErrorInfo (0, errorInfo);
436 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
437 public static int GetHRForLastWin32Error()
440 throw new PlatformNotSupportedException ();
442 throw new NotImplementedException ();
446 #if !FULL_AOT_RUNTIME
447 [MethodImplAttribute (MethodImplOptions.InternalCall)]
448 private extern static IntPtr GetIDispatchForObjectInternal (object o);
450 public static IntPtr GetIDispatchForObject (object o)
452 IntPtr pUnk = GetIDispatchForObjectInternal (o);
453 // Internal method does not AddRef
459 public static IntPtr GetIDispatchForObjectInContext (object o)
461 throw new NotImplementedException ();
465 public static IntPtr GetITypeInfoForType (Type t)
467 throw new NotImplementedException ();
471 public static IntPtr GetIUnknownForObjectInContext (object o)
473 throw new NotImplementedException ();
477 [Obsolete ("This method has been deprecated")]
478 public static IntPtr GetManagedThunkForUnmanagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
480 throw new NotImplementedException ();
484 public static MemberInfo GetMethodInfoForComSlot (Type t, int slot, ref ComMemberType memberType)
486 throw new NotImplementedException ();
489 [MethodImplAttribute (MethodImplOptions.InternalCall)]
490 private extern static IntPtr GetIUnknownForObjectInternal (object o);
492 #endif // !FULL_AOT_RUNTIME
494 public static IntPtr GetIUnknownForObject (object o)
497 throw new PlatformNotSupportedException ();
499 IntPtr pUnk = GetIUnknownForObjectInternal (o);
500 // Internal method does not AddRef
506 public static void GetNativeVariantForObject (object obj, IntPtr pDstNativeVariant)
509 throw new PlatformNotSupportedException ();
511 Variant vt = new Variant();
513 Marshal.StructureToPtr(vt, pDstNativeVariant, false);
517 public static void GetNativeVariantForObject<T> (T obj, IntPtr pDstNativeVariant) {
518 GetNativeVariantForObject ((object)obj, pDstNativeVariant);
521 #if !MOBILE && !FULL_AOT_RUNTIME
522 [MethodImplAttribute (MethodImplOptions.InternalCall)]
523 private static extern object GetObjectForCCW (IntPtr pUnk);
526 public static object GetObjectForIUnknown (IntPtr pUnk)
528 #if MOBILE || FULL_AOT_RUNTIME
529 throw new PlatformNotSupportedException ();
531 object obj = GetObjectForCCW (pUnk);
534 ComInteropProxy proxy = ComInteropProxy.GetProxy (pUnk, typeof (__ComObject));
535 obj = proxy.GetTransparentProxy ();
541 public static object GetObjectForNativeVariant (IntPtr pSrcNativeVariant)
544 throw new PlatformNotSupportedException ();
546 Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
547 return vt.GetValue();
551 public static T GetObjectForNativeVariant<T> (IntPtr pSrcNativeVariant)
554 throw new PlatformNotSupportedException ();
556 Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
557 return (T)vt.GetValue();
561 public static object[] GetObjectsForNativeVariants (IntPtr aSrcNativeVariant, int cVars)
564 throw new PlatformNotSupportedException ();
567 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
568 object[] objects = new object[cVars];
569 for (int i = 0; i < cVars; i++)
570 objects[i] = GetObjectForNativeVariant ((IntPtr)(aSrcNativeVariant.ToInt64 () +
571 i * SizeOf (typeof(Variant))));
576 public static T[] GetObjectsForNativeVariants<T> (IntPtr aSrcNativeVariant, int cVars)
579 throw new PlatformNotSupportedException ();
582 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
583 T[] objects = new T[cVars];
584 for (int i = 0; i < cVars; i++)
585 objects[i] = GetObjectForNativeVariant<T> ((IntPtr)(aSrcNativeVariant.ToInt64 () +
586 i * SizeOf (typeof(Variant))));
592 public static int GetStartComSlot (Type t)
595 throw new PlatformNotSupportedException ();
597 throw new NotImplementedException ();
601 #if !FULL_AOT_RUNTIME
603 [Obsolete ("This method has been deprecated")]
604 public static Thread GetThreadFromFiberCookie (int cookie)
606 throw new NotImplementedException ();
609 public static object GetTypedObjectForIUnknown (IntPtr pUnk, Type t)
611 ComInteropProxy proxy = new ComInteropProxy (pUnk, t);
612 __ComObject co = (__ComObject)proxy.GetTransparentProxy ();
613 foreach (Type itf in t.GetInterfaces ()) {
614 if ((itf.Attributes & TypeAttributes.Import) == TypeAttributes.Import) {
615 if (co.GetInterface (itf) == IntPtr.Zero)
623 public static Type GetTypeForITypeInfo (IntPtr piTypeInfo)
625 throw new NotImplementedException ();
630 public static string GetTypeInfoName (UCOMITypeInfo pTI)
632 throw new NotImplementedException ();
637 public static Guid GetTypeLibGuid (UCOMITypeLib pTLB)
639 throw new NotImplementedException ();
643 public static Guid GetTypeLibGuid (ITypeLib typelib)
645 throw new NotImplementedException ();
649 public static Guid GetTypeLibGuidForAssembly (Assembly asm)
651 throw new NotImplementedException ();
656 public static int GetTypeLibLcid (UCOMITypeLib pTLB)
658 throw new NotImplementedException ();
662 public static int GetTypeLibLcid (ITypeLib typelib)
664 throw new NotImplementedException ();
669 public static string GetTypeLibName (UCOMITypeLib pTLB)
671 throw new NotImplementedException ();
675 public static string GetTypeLibName (ITypeLib typelib)
677 throw new NotImplementedException ();
681 public static void GetTypeLibVersionForAssembly (Assembly inputAssembly, out int majorVersion, out int minorVersion)
683 throw new NotImplementedException ();
687 [Obsolete ("This method has been deprecated")]
688 public static IntPtr GetUnmanagedThunkForManagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
690 throw new NotImplementedException ();
694 public static bool IsTypeVisibleFromCom (Type t)
696 throw new NotImplementedException ();
700 public static int NumParamBytes (MethodInfo m)
702 throw new NotImplementedException ();
704 #endif // !FULL_AOT_RUNTIME
706 public static Type GetTypeFromCLSID (Guid clsid)
708 throw new PlatformNotSupportedException ();
711 public static string GetTypeInfoName (ITypeInfo typeInfo)
713 throw new PlatformNotSupportedException ();
716 public static object GetUniqueObjectForIUnknown (IntPtr unknown)
718 throw new PlatformNotSupportedException ();
722 [MethodImplAttribute (MethodImplOptions.InternalCall)]
723 public extern static bool IsComObject (object o);
725 public static bool IsComObject (object o)
727 throw new PlatformNotSupportedException ();
731 [MethodImplAttribute(MethodImplOptions.InternalCall)]
732 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
733 public static extern int GetLastWin32Error();
735 [MethodImplAttribute(MethodImplOptions.InternalCall)]
736 public extern static IntPtr OffsetOf (Type t, string fieldName);
738 public static IntPtr OffsetOf<T> (string fieldName) {
739 return OffsetOf (typeof (T), fieldName);
742 [MethodImplAttribute(MethodImplOptions.InternalCall)]
743 public extern static void Prelink (MethodInfo m);
745 [MethodImplAttribute(MethodImplOptions.InternalCall)]
746 public extern static void PrelinkAll (Type c);
748 [MethodImplAttribute(MethodImplOptions.InternalCall)]
749 public extern static string PtrToStringAnsi (IntPtr ptr);
751 [MethodImplAttribute(MethodImplOptions.InternalCall)]
752 public extern static string PtrToStringAnsi (IntPtr ptr, int len);
754 public static string PtrToStringAuto (IntPtr ptr)
756 return SystemDefaultCharSize == 2
757 ? PtrToStringUni (ptr) : PtrToStringAnsi (ptr);
760 public static string PtrToStringAuto (IntPtr ptr, int len)
762 return SystemDefaultCharSize == 2
763 ? PtrToStringUni (ptr, len) : PtrToStringAnsi (ptr, len);
766 [MethodImplAttribute(MethodImplOptions.InternalCall)]
767 public extern static string PtrToStringUni (IntPtr ptr);
769 [MethodImplAttribute(MethodImplOptions.InternalCall)]
770 public extern static string PtrToStringUni (IntPtr ptr, int len);
773 [MethodImplAttribute(MethodImplOptions.InternalCall)]
774 public extern static string PtrToStringBSTR (IntPtr ptr);
776 public static string PtrToStringBSTR (IntPtr ptr)
778 throw new NotImplementedException ();
782 [MethodImplAttribute(MethodImplOptions.InternalCall)]
784 public extern static void PtrToStructure (IntPtr ptr, object structure);
786 [MethodImplAttribute(MethodImplOptions.InternalCall)]
788 public extern static object PtrToStructure (IntPtr ptr, Type structureType);
790 public static void PtrToStructure<T> (IntPtr ptr, T structure) {
791 PtrToStructure (ptr, (object)structure);
794 public static T PtrToStructure<T> (IntPtr ptr) {
795 return (T) PtrToStructure (ptr, typeof (T));
799 [MethodImplAttribute (MethodImplOptions.InternalCall)]
800 private extern static int QueryInterfaceInternal (IntPtr pUnk, ref Guid iid, out IntPtr ppv);
803 public static int QueryInterface (IntPtr pUnk, ref Guid iid, out IntPtr ppv)
806 if (pUnk == IntPtr.Zero)
807 throw new ArgumentException ("Value cannot be null.", "pUnk");
808 return QueryInterfaceInternal (pUnk, ref iid, out ppv);
810 throw new NotImplementedException ();
814 public static byte ReadByte (IntPtr ptr)
821 public static byte ReadByte (IntPtr ptr, int ofs) {
823 return *((byte*)ptr + ofs);
828 [SuppressUnmanagedCodeSecurity]
829 public static byte ReadByte ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
831 throw new NotImplementedException ();
834 public unsafe static short ReadInt16 (IntPtr ptr)
836 byte *addr = (byte *) ptr;
838 // The mono JIT can't inline this due to the hight number of calls
839 // return ReadInt16 (ptr, 0);
841 if (((uint)addr & 1) == 0)
842 return *(short*)addr;
845 Buffer.Memcpy ((byte*)&s, (byte*)ptr, 2);
849 public unsafe static short ReadInt16 (IntPtr ptr, int ofs)
851 byte *addr = ((byte *) ptr) + ofs;
853 if (((uint) addr & 1) == 0)
854 return *(short*)addr;
857 Buffer.Memcpy ((byte*)&s, addr, 2);
862 [SuppressUnmanagedCodeSecurity]
863 public static short ReadInt16 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
865 throw new NotImplementedException ();
868 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
869 public unsafe static int ReadInt32 (IntPtr ptr)
871 byte *addr = (byte *) ptr;
873 if (((uint)addr & 3) == 0)
877 Buffer.Memcpy ((byte*)&s, addr, 4);
881 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
882 public unsafe static int ReadInt32 (IntPtr ptr, int ofs)
884 byte *addr = ((byte *) ptr) + ofs;
886 if ((((int) addr) & 3) == 0)
890 Buffer.Memcpy ((byte*)&s, addr, 4);
895 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
897 [SuppressUnmanagedCodeSecurity]
898 public static int ReadInt32 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
900 throw new NotImplementedException ();
903 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
904 public unsafe static long ReadInt64 (IntPtr ptr)
906 byte *addr = (byte *) ptr;
908 // The real alignment might be 4 on some platforms, but this is just an optimization,
909 // so it doesn't matter.
910 if (((uint) addr & 7) == 0)
914 Buffer.Memcpy ((byte*)&s, addr, 8);
918 public unsafe static long ReadInt64 (IntPtr ptr, int ofs)
920 byte *addr = ((byte *) ptr) + ofs;
922 if (((uint) addr & 7) == 0)
926 Buffer.Memcpy ((byte*)&s, addr, 8);
930 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
932 [SuppressUnmanagedCodeSecurity]
933 public static long ReadInt64 ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
935 throw new NotImplementedException ();
938 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
939 public static IntPtr ReadIntPtr (IntPtr ptr)
941 if (IntPtr.Size == 4)
942 return (IntPtr)ReadInt32 (ptr);
944 return (IntPtr)ReadInt64 (ptr);
947 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
948 public static IntPtr ReadIntPtr (IntPtr ptr, int ofs)
950 if (IntPtr.Size == 4)
951 return (IntPtr)ReadInt32 (ptr, ofs);
953 return (IntPtr)ReadInt64 (ptr, ofs);
956 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
958 public static IntPtr ReadIntPtr ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
960 throw new NotImplementedException ();
963 [MethodImplAttribute (MethodImplOptions.InternalCall)]
964 public extern static IntPtr ReAllocCoTaskMem (IntPtr pv, int cb);
966 [MethodImplAttribute(MethodImplOptions.InternalCall)]
967 public extern static IntPtr ReAllocHGlobal (IntPtr pv, IntPtr cb);
970 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
971 [MethodImplAttribute (MethodImplOptions.InternalCall)]
972 private extern static int ReleaseInternal (IntPtr pUnk);
975 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
976 public static int Release (IntPtr pUnk)
979 if (pUnk == IntPtr.Zero)
980 throw new ArgumentException ("Value cannot be null.", "pUnk");
982 return ReleaseInternal (pUnk);
984 throw new NotImplementedException ();
988 #if !FULL_AOT_RUNTIME
989 [MethodImplAttribute (MethodImplOptions.InternalCall)]
990 private extern static int ReleaseComObjectInternal (object co);
993 public static int ReleaseComObject (object o)
996 throw new PlatformNotSupportedException ();
999 throw new ArgumentException ("Value cannot be null.", "o");
1000 if (!IsComObject (o))
1001 throw new ArgumentException ("Value must be a Com object.", "o");
1002 return ReleaseComObjectInternal (o);
1006 #if !FULL_AOT_RUNTIME
1009 public static void ReleaseThreadCache()
1011 throw new NotImplementedException ();
1014 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
1015 public static bool SetComObjectData (object obj, object key, object data)
1017 throw new NotSupportedException ("MSDN states user code should never need to call this method.");
1022 public static int SizeOf (object structure)
1024 return SizeOf (structure.GetType ());
1027 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1028 public extern static int SizeOf (Type t);
1030 public static int SizeOf<T> () {
1031 return SizeOf (typeof (T));
1034 public static int SizeOf<T> (T structure) {
1035 return SizeOf (structure.GetType ());
1038 internal static uint SizeOfType (Type type)
1040 return (uint) SizeOf (type);
1043 internal static uint AlignedSizeOf<T> () where T : struct
1045 uint size = SizeOfType (typeof (T));
1046 if (size == 1 || size == 2)
1048 if (IntPtr.Size == 8 && size == 4)
1050 return (size + 3) & (~((uint)3));
1053 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1054 public extern static IntPtr StringToBSTR (string s);
1057 // I believe this is wrong, because in Mono and in P/Invoke
1058 // we treat "Ansi" conversions as UTF-8 conversions, while
1059 // this one does not do this
1061 public static IntPtr StringToCoTaskMemAnsi (string s)
1063 int length = s.Length + 1;
1064 IntPtr ctm = AllocCoTaskMem (length);
1066 byte[] asBytes = new byte[length];
1067 for (int i = 0; i < s.Length; i++)
1068 asBytes[i] = (byte)s[i];
1069 asBytes[s.Length] = 0;
1071 copy_to_unmanaged (asBytes, 0, ctm, length);
1075 public static IntPtr StringToCoTaskMemAuto (string s)
1077 return SystemDefaultCharSize == 2
1078 ? StringToCoTaskMemUni (s) : StringToCoTaskMemAnsi (s);
1081 public static IntPtr StringToCoTaskMemUni (string s)
1083 int length = s.Length + 1;
1084 IntPtr ctm = AllocCoTaskMem (length * 2);
1086 char[] asChars = new char[length];
1087 s.CopyTo (0, asChars, 0, s.Length);
1088 asChars[s.Length] = '\0';
1090 copy_to_unmanaged (asChars, 0, ctm, length);
1094 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1095 public extern static IntPtr StringToHGlobalAnsi (string s);
1097 public static IntPtr StringToHGlobalAuto (string s)
1099 return SystemDefaultCharSize == 2
1100 ? StringToHGlobalUni (s) : StringToHGlobalAnsi (s);
1103 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1104 public extern static IntPtr StringToHGlobalUni (string s);
1106 public static IntPtr SecureStringToBSTR (SecureString s)
1109 throw new ArgumentNullException ("s");
1111 byte[] buffer = s.GetBuffer ();
1114 // SecureString doesn't take endian-ness into account.
1115 // Therefore swap bytes here before we send it to c-side if little-endian.
1116 if (BitConverter.IsLittleEndian) {
1117 for (int i = 0; i < buffer.Length; i += 2) {
1119 buffer[i] = buffer[i + 1];
1123 return BufferToBSTR (buffer, len);
1126 public static IntPtr SecureStringToCoTaskMemAnsi (SecureString s)
1129 throw new ArgumentNullException ("s");
1131 IntPtr ctm = AllocCoTaskMem (len + 1);
1132 byte [] copy = new byte [len+1];
1135 byte [] buffer = s.GetBuffer ();
1137 for (; i < len; i++, j += 2){
1138 copy [i] = buffer [j+1];
1143 copy_to_unmanaged (copy, 0, ctm, len+1);
1145 // Ensure that we clear the buffer.
1146 for (int i = len; i > 0; ){
1154 public static IntPtr SecureStringToCoTaskMemUnicode (SecureString s)
1157 throw new ArgumentNullException ("s");
1159 IntPtr ctm = AllocCoTaskMem (len * 2 + 2);
1160 byte [] buffer = null;
1162 buffer = s.GetBuffer ();
1163 for (int i = 0; i < len; i++)
1164 WriteInt16 (ctm, i * 2, (short) ((buffer [(i*2)] << 8) | (buffer [i*2+1])));
1165 WriteInt16 (ctm, buffer.Length, 0);
1168 for (int i = buffer.Length; i > 0; ){
1176 public static IntPtr SecureStringToGlobalAllocAnsi (SecureString s)
1179 throw new ArgumentNullException ("s");
1180 return SecureStringToCoTaskMemAnsi (s);
1183 public static IntPtr SecureStringToGlobalAllocUnicode (SecureString s)
1186 throw new ArgumentNullException ("s");
1187 return SecureStringToCoTaskMemUnicode (s);
1190 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
1192 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1193 public extern static void StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld);
1195 public static void StructureToPtr<T> (T structure, IntPtr ptr, bool fDeleteOld) {
1196 StructureToPtr ((object)structure, ptr, fDeleteOld);
1199 public static void ThrowExceptionForHR (int errorCode) {
1200 Exception ex = GetExceptionForHR (errorCode);
1205 public static void ThrowExceptionForHR (int errorCode, IntPtr errorInfo) {
1206 Exception ex = GetExceptionForHR (errorCode, errorInfo);
1212 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1213 public extern static IntPtr BufferToBSTR (Array ptr, int slen);
1215 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1216 public extern static IntPtr UnsafeAddrOfPinnedArrayElement (Array arr, int index);
1218 public static IntPtr UnsafeAddrOfPinnedArrayElement<T> (T[] arr, int index) {
1219 return UnsafeAddrOfPinnedArrayElement ((Array)arr, index);
1222 public static void WriteByte (IntPtr ptr, byte val)
1229 public static void WriteByte (IntPtr ptr, int ofs, byte val) {
1231 *(byte*)(IntPtr.Add (ptr, ofs)) = val;
1236 [SuppressUnmanagedCodeSecurity]
1237 public static void WriteByte ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, byte val)
1239 throw new NotImplementedException ();
1242 public static unsafe void WriteInt16 (IntPtr ptr, short val)
1244 byte *addr = (byte *) ptr;
1246 if (((uint)addr & 1) == 0)
1247 *(short*)addr = val;
1249 Buffer.Memcpy (addr, (byte*)&val, 2);
1252 public static unsafe void WriteInt16 (IntPtr ptr, int ofs, short val)
1254 byte *addr = ((byte *) ptr) + ofs;
1256 if (((uint)addr & 1) == 0)
1257 *(short*)addr = val;
1259 Buffer.Memcpy (addr, (byte*)&val, 2);
1264 [SuppressUnmanagedCodeSecurity]
1265 public static void WriteInt16 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, short val)
1267 throw new NotImplementedException ();
1270 public static void WriteInt16 (IntPtr ptr, char val)
1272 WriteInt16 (ptr, 0, (short)val);
1275 public static void WriteInt16 (IntPtr ptr, int ofs, char val)
1277 WriteInt16 (ptr, ofs, (short)val);
1281 public static void WriteInt16([In, Out] object ptr, int ofs, char val)
1283 throw new NotImplementedException ();
1286 public static unsafe void WriteInt32 (IntPtr ptr, int val)
1288 byte *addr = (byte *) ptr;
1290 if (((uint)addr & 3) == 0)
1293 Buffer.Memcpy (addr, (byte*)&val, 4);
1297 public unsafe static void WriteInt32 (IntPtr ptr, int ofs, int val)
1299 byte *addr = ((byte *) ptr) + ofs;
1301 if (((uint)addr & 3) == 0)
1304 Buffer.Memcpy (addr, (byte*)&val, 4);
1309 [SuppressUnmanagedCodeSecurity]
1310 public static void WriteInt32([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, int val)
1312 throw new NotImplementedException ();
1315 public static unsafe void WriteInt64 (IntPtr ptr, long val)
1317 byte *addr = (byte *) ptr;
1319 // The real alignment might be 4 on some platforms, but this is just an optimization,
1320 // so it doesn't matter.
1321 if (((uint)addr & 7) == 0)
1324 Buffer.Memcpy (addr, (byte*)&val, 8);
1327 public static unsafe void WriteInt64 (IntPtr ptr, int ofs, long val)
1329 byte *addr = ((byte *) ptr) + ofs;
1331 // The real alignment might be 4 on some platforms, but this is just an optimization,
1332 // so it doesn't matter.
1333 if (((uint)addr & 7) == 0)
1336 Buffer.Memcpy (addr, (byte*)&val, 8);
1340 [SuppressUnmanagedCodeSecurity]
1341 public static void WriteInt64 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, long val)
1343 throw new NotImplementedException ();
1346 public static void WriteIntPtr (IntPtr ptr, IntPtr val)
1348 if (IntPtr.Size == 4)
1349 WriteInt32 (ptr, (int)val);
1351 WriteInt64 (ptr, (long)val);
1354 public static void WriteIntPtr (IntPtr ptr, int ofs, IntPtr val)
1356 if (IntPtr.Size == 4)
1357 WriteInt32 (ptr, ofs, (int)val);
1359 WriteInt64 (ptr, ofs, (long)val);
1363 public static void WriteIntPtr([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, IntPtr val)
1365 throw new NotImplementedException ();
1368 private static Exception ConvertHrToException (int errorCode)
1370 const int MSEE_E_APPDOMAINUNLOADED = unchecked ((int)0x80131014L);
1371 const int COR_E_APPLICATION = unchecked ((int)0x80131600L);
1372 const int E_INVALIDARG = unchecked ((int)0x80070057);
1373 const int COR_E_ARGUMENTOUTOFRANGE = unchecked ((int)0x80131502L);
1374 const int COR_E_ARITHMETIC = unchecked ((int)0x80070216);
1375 const int COR_E_ARRAYTYPEMISMATCH = unchecked ((int)0x80131503L);
1376 const int COR_E_BADIMAGEFORMAT = unchecked ((int)0x8007000BL);
1377 const int ERROR_BAD_FORMAT = unchecked ((int)0x0B);
1378 //const int COR_E_COMEMULATE_ERROR = unchecked ((int)?);
1379 const int COR_E_CONTEXTMARSHAL = unchecked ((int)0x80131504L);
1380 //const int COR_E_CORE = unchecked ((int)?);
1381 const int NTE_FAIL = unchecked ((int)0x80090020L);
1382 const int COR_E_DIRECTORYNOTFOUND = unchecked ((int)0x80070003L);
1383 const int ERROR_PATH_NOT_FOUND = unchecked ((int)0x03);
1384 const int COR_E_DIVIDEBYZERO = unchecked ((int)0x80020012L);
1385 const int COR_E_DUPLICATEWAITOBJECT = unchecked ((int)0x80131529L);
1386 const int COR_E_ENDOFSTREAM = unchecked ((int)0x80070026L);
1387 const int COR_E_TYPELOAD = unchecked ((int)0x80131522L);
1388 const int COR_E_EXCEPTION = unchecked ((int)0x80131500L);
1389 const int COR_E_EXECUTIONENGINE = unchecked ((int)0x80131506L);
1390 const int COR_E_FIELDACCESS = unchecked ((int)0x80131507L);
1391 const int COR_E_FILENOTFOUND = unchecked ((int)0x80070002L);
1392 const int ERROR_FILE_NOT_FOUND = unchecked ((int)0x02);
1393 const int COR_E_FORMAT = unchecked ((int)0x80131537L);
1394 const int COR_E_INDEXOUTOFRANGE = unchecked ((int)0x80131508L);
1395 const int COR_E_INVALIDCAST = unchecked ((int)0x80004002L);
1396 const int COR_E_INVALIDCOMOBJECT = unchecked ((int)0x80131527L);
1397 const int COR_E_INVALIDFILTERCRITERIA = unchecked ((int)0x80131601L);
1398 const int COR_E_INVALIDOLEVARIANTTYPE = unchecked ((int)0x80131531L);
1399 const int COR_E_INVALIDOPERATION = unchecked ((int)0x80131509L);
1400 const int COR_E_IO = unchecked ((int)0x80131620L);
1401 const int COR_E_MEMBERACCESS = unchecked ((int)0x8013151AL);
1402 const int COR_E_METHODACCESS = unchecked ((int)0x80131510L);
1403 const int COR_E_MISSINGFIELD = unchecked ((int)0x80131511L);
1404 const int COR_E_MISSINGMANIFESTRESOURCE = unchecked ((int)0x80131532L);
1405 const int COR_E_MISSINGMEMBER = unchecked ((int)0x80131512L);
1406 const int COR_E_MISSINGMETHOD = unchecked ((int)0x80131513L);
1407 const int COR_E_MULTICASTNOTSUPPORTED = unchecked ((int)0x80131514L);
1408 const int COR_E_NOTFINITENUMBER = unchecked ((int)0x80131528L);
1409 const int E_NOTIMPL = unchecked ((int)0x80004001L);
1410 const int COR_E_NOTSUPPORTED = unchecked ((int)0x80131515L);
1411 const int COR_E_NULLREFERENCE = unchecked ((int)0x80004003L);
1412 const int E_OUTOFMEMORY = unchecked ((int)0x8007000EL);
1413 const int COR_E_OVERFLOW = unchecked ((int)0x80131516L);
1414 const int COR_E_PATHTOOLONG = unchecked ((int)0x800700CEL);
1415 const int ERROR_FILENAME_EXCED_RANGE = unchecked ((int)0xCE);
1416 const int COR_E_RANK = unchecked ((int)0x80131517L);
1417 const int COR_E_REFLECTIONTYPELOAD = unchecked ((int)0x80131602L);
1418 const int COR_E_REMOTING = unchecked ((int)0x8013150BL);
1419 const int COR_E_SAFEARRAYTYPEMISMATCH = unchecked ((int)0x80131533L);
1420 const int COR_E_SECURITY = unchecked ((int)0x8013150AL);
1421 const int COR_E_SERIALIZATION = unchecked ((int)0x8013150CL);
1422 const int COR_E_STACKOVERFLOW = unchecked ((int)0x800703E9L);
1423 const int ERROR_STACK_OVERFLOW = unchecked ((int)0x03E9);
1424 const int COR_E_SYNCHRONIZATIONLOCK = unchecked ((int)0x80131518L);
1425 const int COR_E_SYSTEM = unchecked ((int)0x80131501L);
1426 const int COR_E_TARGET = unchecked ((int)0x80131603L);
1427 const int COR_E_TARGETINVOCATION = unchecked ((int)0x80131604L);
1428 const int COR_E_TARGETPARAMCOUNT = unchecked ((int)0x8002000EL);
1429 //const int COR_E_THREADABORTED = unchecked ((int)0x80131530L);
1430 const int COR_E_THREADINTERRUPTED = unchecked ((int)0x80131519L);
1431 const int COR_E_THREADSTATE = unchecked ((int)0x80131520L);
1432 //const int COR_E_THREADSTOP = unchecked ((int)0x80131521L);
1433 const int COR_E_TYPEINITIALIZATION = unchecked ((int)0x80131534L);
1434 const int COR_E_VERIFICATION = unchecked ((int)0x8013150DL);
1435 //const int COR_E_WEAKREFERENCE = unchecked ((int)?);
1436 //const int COR_E_VTABLECALLSNOTSUPPORTED = unchecked ((int));
1438 switch (errorCode) {
1439 case MSEE_E_APPDOMAINUNLOADED:
1440 return new AppDomainUnloadedException ();
1441 case COR_E_APPLICATION:
1442 return new ApplicationException ();
1444 return new ArgumentException ();
1445 case COR_E_ARGUMENTOUTOFRANGE:
1446 return new ArgumentOutOfRangeException ();
1447 case COR_E_ARITHMETIC:
1448 return new ArithmeticException ();
1449 case COR_E_ARRAYTYPEMISMATCH:
1450 return new ArrayTypeMismatchException ();
1451 case COR_E_BADIMAGEFORMAT:
1452 case ERROR_BAD_FORMAT:
1453 return new BadImageFormatException ();
1454 // case COR_E_COMEMULATE_ERROR:
1455 // return new COMEmulateException ();
1456 case COR_E_CONTEXTMARSHAL:
1457 return new ContextMarshalException ();
1459 // return new CoreException ();
1461 return new System.Security.Cryptography.CryptographicException ();
1462 case COR_E_DIRECTORYNOTFOUND:
1463 case ERROR_PATH_NOT_FOUND:
1464 return new System.IO.DirectoryNotFoundException ();
1465 case COR_E_DIVIDEBYZERO:
1466 return new DivideByZeroException ();
1467 case COR_E_DUPLICATEWAITOBJECT:
1468 return new DuplicateWaitObjectException ();
1469 case COR_E_ENDOFSTREAM:
1470 return new System.IO.EndOfStreamException ();
1471 case COR_E_EXCEPTION:
1472 return new Exception ();
1473 case COR_E_EXECUTIONENGINE:
1474 return new ExecutionEngineException ();
1475 case COR_E_FIELDACCESS:
1476 return new FieldAccessException ();
1477 case COR_E_FILENOTFOUND:
1478 case ERROR_FILE_NOT_FOUND:
1479 return new System.IO.FileNotFoundException ();
1481 return new FormatException ();
1482 case COR_E_INDEXOUTOFRANGE:
1483 return new IndexOutOfRangeException ();
1484 case COR_E_INVALIDCAST:
1485 // E_NOINTERFACE has same value as COR_E_INVALIDCAST
1486 return new InvalidCastException ();
1487 case COR_E_INVALIDCOMOBJECT:
1488 return new InvalidComObjectException ();
1489 case COR_E_INVALIDFILTERCRITERIA:
1490 return new InvalidFilterCriteriaException ();
1491 case COR_E_INVALIDOLEVARIANTTYPE:
1492 return new InvalidOleVariantTypeException ();
1493 case COR_E_INVALIDOPERATION:
1494 return new InvalidOperationException ();
1496 return new System.IO.IOException ();
1497 case COR_E_MEMBERACCESS:
1498 return new MemberAccessException ();
1499 case COR_E_METHODACCESS:
1500 return new MethodAccessException ();
1501 case COR_E_MISSINGFIELD:
1502 return new MissingFieldException ();
1503 case COR_E_MISSINGMANIFESTRESOURCE:
1504 return new System.Resources.MissingManifestResourceException ();
1505 case COR_E_MISSINGMEMBER:
1506 return new MissingMemberException ();
1507 case COR_E_MISSINGMETHOD:
1508 return new MissingMethodException ();
1509 case COR_E_MULTICASTNOTSUPPORTED:
1510 return new MulticastNotSupportedException ();
1511 case COR_E_NOTFINITENUMBER:
1512 return new NotFiniteNumberException ();
1514 return new NotImplementedException ();
1515 case COR_E_NOTSUPPORTED:
1516 return new NotSupportedException ();
1517 case COR_E_NULLREFERENCE:
1518 // E_POINTER has the same value as COR_E_NULLREFERENCE
1519 return new NullReferenceException ();
1521 // COR_E_OUTOFMEMORY has the same value as E_OUTOFMEMORY
1522 return new OutOfMemoryException ();
1523 case COR_E_OVERFLOW:
1524 return new OverflowException ();
1525 case COR_E_PATHTOOLONG:
1526 case ERROR_FILENAME_EXCED_RANGE:
1527 return new System.IO.PathTooLongException ();
1529 return new RankException ();
1530 case COR_E_REFLECTIONTYPELOAD:
1531 return new System.Reflection.ReflectionTypeLoadException (new Type[] { }, new Exception[] { });
1532 case COR_E_REMOTING:
1533 return new System.Runtime.Remoting.RemotingException ();
1534 case COR_E_SAFEARRAYTYPEMISMATCH:
1535 return new SafeArrayTypeMismatchException ();
1536 case COR_E_SECURITY:
1537 return new SecurityException ();
1538 case COR_E_SERIALIZATION:
1539 return new System.Runtime.Serialization.SerializationException ();
1540 case COR_E_STACKOVERFLOW:
1541 case ERROR_STACK_OVERFLOW:
1542 return new StackOverflowException ();
1543 case COR_E_SYNCHRONIZATIONLOCK:
1544 return new SynchronizationLockException ();
1546 return new SystemException ();
1548 return new TargetException ();
1549 case COR_E_TARGETINVOCATION:
1550 return new System.Reflection.TargetInvocationException (null);
1551 case COR_E_TARGETPARAMCOUNT:
1552 return new TargetParameterCountException ();
1553 // case COR_E_THREADABORTED:
1554 // ThreadAbortException c'tor is inaccessible
1555 // return new System.Threading.ThreadAbortException ();
1556 case COR_E_THREADINTERRUPTED:
1557 return new ThreadInterruptedException ();
1558 case COR_E_THREADSTATE:
1559 return new ThreadStateException ();
1560 // case COR_E_THREADSTOP:
1561 // ThreadStopException does not exist
1562 // return new System.Threading.ThreadStopException ();
1563 case COR_E_TYPELOAD:
1564 return new TypeLoadException ();
1565 // MSDN lists COR_E_TYPELOAD twice with different exceptions.
1566 // return new EntryPointNotFoundException ();
1567 case COR_E_TYPEINITIALIZATION:
1568 return new TypeInitializationException("", null);
1569 case COR_E_VERIFICATION:
1570 return new VerificationException ();
1571 // case COR_E_WEAKREFERENCE:
1572 // return new WeakReferenceException ();
1573 // case COR_E_VTABLECALLSNOTSUPPORTED:
1574 // return new VTableCallsNotSupportedException ();
1577 return new COMException ("", errorCode);
1581 #if FEATURE_COMINTEROP
1582 [DllImport ("oleaut32.dll", CharSet=CharSet.Unicode, EntryPoint = "SetErrorInfo")]
1583 static extern int _SetErrorInfo (int dwReserved,
1584 [MarshalAs(UnmanagedType.Interface)] IErrorInfo pIErrorInfo);
1586 [DllImport ("oleaut32.dll", CharSet=CharSet.Unicode, EntryPoint = "GetErrorInfo")]
1587 static extern int _GetErrorInfo (int dwReserved,
1588 [MarshalAs(UnmanagedType.Interface)] out IErrorInfo ppIErrorInfo);
1590 static bool SetErrorInfoNotAvailable;
1591 static bool GetErrorInfoNotAvailable;
1593 internal static int SetErrorInfo (int dwReserved, IErrorInfo errorInfo)
1598 if (SetErrorInfoNotAvailable)
1602 retVal = _SetErrorInfo (dwReserved, errorInfo);
1605 // ignore any exception - probably there's no suitable SetErrorInfo
1606 // method available.
1607 SetErrorInfoNotAvailable = true;
1612 internal static int GetErrorInfo (int dwReserved, out IErrorInfo errorInfo)
1617 if (GetErrorInfoNotAvailable)
1621 retVal = _GetErrorInfo (dwReserved, out errorInfo);
1624 // ignore any exception - probably there's no suitable GetErrorInfo
1625 // method available.
1626 GetErrorInfoNotAvailable = true;
1631 public static Exception GetExceptionForHR (int errorCode)
1633 return GetExceptionForHR (errorCode, IntPtr.Zero);
1636 public static Exception GetExceptionForHR (int errorCode, IntPtr errorInfo)
1638 #if FEATURE_COMINTEROP
1639 IErrorInfo info = null;
1640 if (errorInfo != (IntPtr)(-1)) {
1641 if (errorInfo == IntPtr.Zero) {
1642 if (GetErrorInfo (0, out info) != 0) {
1646 info = Marshal.GetObjectForIUnknown (errorInfo) as IErrorInfo;
1650 if (info is ManagedErrorInfo && ((ManagedErrorInfo) info).Exception._HResult == errorCode) {
1651 return ((ManagedErrorInfo) info).Exception;
1654 Exception e = ConvertHrToException (errorCode);
1655 if (info != null && e != null) {
1657 info.GetHelpContext (out helpContext);
1659 info.GetSource (out str);
1661 info.GetDescription (out str);
1663 info.GetHelpFile (out str);
1665 if (helpContext == 0) {
1668 e.HelpLink = string.Format ("{0}#{1}", str, helpContext);
1673 return ConvertHrToException (errorCode);
1677 public static int FinalReleaseComObject (object o)
1679 while (ReleaseComObject (o) != 0);
1683 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1684 private static extern Delegate GetDelegateForFunctionPointerInternal (IntPtr ptr, Type t);
1686 public static Delegate GetDelegateForFunctionPointer (IntPtr ptr, Type t)
1689 throw new ArgumentNullException ("t");
1690 if (!t.IsSubclassOf (typeof (MulticastDelegate)) || (t == typeof (MulticastDelegate)))
1691 throw new ArgumentException ("Type is not a delegate", "t");
1692 if (t.IsGenericType)
1693 throw new ArgumentException ("The specified Type must not be a generic type definition.");
1694 if (ptr == IntPtr.Zero)
1695 throw new ArgumentNullException ("ptr");
1697 return GetDelegateForFunctionPointerInternal (ptr, t);
1700 public static TDelegate GetDelegateForFunctionPointer<TDelegate> (IntPtr ptr) {
1701 return (TDelegate) (object) GetDelegateForFunctionPointer (ptr, typeof (TDelegate));
1704 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1705 private static extern IntPtr GetFunctionPointerForDelegateInternal (Delegate d);
1707 public static IntPtr GetFunctionPointerForDelegate (Delegate d)
1710 throw new ArgumentNullException ("d");
1712 return GetFunctionPointerForDelegateInternal (d);
1715 public static IntPtr GetFunctionPointerForDelegate<TDelegate> (TDelegate d) {
1717 throw new ArgumentNullException ("d");
1719 return GetFunctionPointerForDelegateInternal ((Delegate)(object)d);
1722 internal static void SetLastWin32Error (int error)