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 FEATURE_COMINTEROP
426 var errorInfo = new ManagedErrorInfo(e);
427 SetErrorInfo (0, errorInfo);
430 #elif FULL_AOT_RUNTIME
431 throw new PlatformNotSupportedException ();
438 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
439 public static int GetHRForLastWin32Error()
442 throw new PlatformNotSupportedException ();
444 throw new NotImplementedException ();
448 #if !FULL_AOT_RUNTIME
449 [MethodImplAttribute (MethodImplOptions.InternalCall)]
450 private extern static IntPtr GetIDispatchForObjectInternal (object o);
452 public static IntPtr GetIDispatchForObject (object o)
454 IntPtr pUnk = GetIDispatchForObjectInternal (o);
455 // Internal method does not AddRef
461 public static IntPtr GetIDispatchForObjectInContext (object o)
463 throw new NotImplementedException ();
467 public static IntPtr GetITypeInfoForType (Type t)
469 throw new NotImplementedException ();
473 public static IntPtr GetIUnknownForObjectInContext (object o)
475 throw new NotImplementedException ();
479 [Obsolete ("This method has been deprecated")]
480 public static IntPtr GetManagedThunkForUnmanagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
482 throw new NotImplementedException ();
486 public static MemberInfo GetMethodInfoForComSlot (Type t, int slot, ref ComMemberType memberType)
488 throw new NotImplementedException ();
491 [MethodImplAttribute (MethodImplOptions.InternalCall)]
492 private extern static IntPtr GetIUnknownForObjectInternal (object o);
494 #endif // !FULL_AOT_RUNTIME
496 public static IntPtr GetIUnknownForObject (object o)
499 throw new PlatformNotSupportedException ();
501 IntPtr pUnk = GetIUnknownForObjectInternal (o);
502 // Internal method does not AddRef
508 public static void GetNativeVariantForObject (object obj, IntPtr pDstNativeVariant)
511 throw new PlatformNotSupportedException ();
513 Variant vt = new Variant();
515 Marshal.StructureToPtr(vt, pDstNativeVariant, false);
519 public static void GetNativeVariantForObject<T> (T obj, IntPtr pDstNativeVariant) {
520 GetNativeVariantForObject ((object)obj, pDstNativeVariant);
523 #if !MOBILE && !FULL_AOT_RUNTIME
524 [MethodImplAttribute (MethodImplOptions.InternalCall)]
525 private static extern object GetObjectForCCW (IntPtr pUnk);
528 public static object GetObjectForIUnknown (IntPtr pUnk)
530 #if MOBILE || FULL_AOT_RUNTIME
531 throw new PlatformNotSupportedException ();
533 object obj = GetObjectForCCW (pUnk);
536 ComInteropProxy proxy = ComInteropProxy.GetProxy (pUnk, typeof (__ComObject));
537 obj = proxy.GetTransparentProxy ();
543 public static object GetObjectForNativeVariant (IntPtr pSrcNativeVariant)
546 throw new PlatformNotSupportedException ();
548 Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
549 return vt.GetValue();
553 public static T GetObjectForNativeVariant<T> (IntPtr pSrcNativeVariant)
556 throw new PlatformNotSupportedException ();
558 Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
559 return (T)vt.GetValue();
563 public static object[] GetObjectsForNativeVariants (IntPtr aSrcNativeVariant, int cVars)
566 throw new PlatformNotSupportedException ();
569 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
570 object[] objects = new object[cVars];
571 for (int i = 0; i < cVars; i++)
572 objects[i] = GetObjectForNativeVariant ((IntPtr)(aSrcNativeVariant.ToInt64 () +
573 i * SizeOf (typeof(Variant))));
578 public static T[] GetObjectsForNativeVariants<T> (IntPtr aSrcNativeVariant, int cVars)
581 throw new PlatformNotSupportedException ();
584 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
585 T[] objects = new T[cVars];
586 for (int i = 0; i < cVars; i++)
587 objects[i] = GetObjectForNativeVariant<T> ((IntPtr)(aSrcNativeVariant.ToInt64 () +
588 i * SizeOf (typeof(Variant))));
594 public static int GetStartComSlot (Type t)
597 throw new PlatformNotSupportedException ();
599 throw new NotImplementedException ();
603 #if !FULL_AOT_RUNTIME
605 [Obsolete ("This method has been deprecated")]
606 public static Thread GetThreadFromFiberCookie (int cookie)
608 throw new NotImplementedException ();
611 public static object GetTypedObjectForIUnknown (IntPtr pUnk, Type t)
613 ComInteropProxy proxy = new ComInteropProxy (pUnk, t);
614 __ComObject co = (__ComObject)proxy.GetTransparentProxy ();
615 foreach (Type itf in t.GetInterfaces ()) {
616 if ((itf.Attributes & TypeAttributes.Import) == TypeAttributes.Import) {
617 if (co.GetInterface (itf) == IntPtr.Zero)
625 public static Type GetTypeForITypeInfo (IntPtr piTypeInfo)
627 throw new NotImplementedException ();
632 public static string GetTypeInfoName (UCOMITypeInfo pTI)
634 throw new NotImplementedException ();
639 public static Guid GetTypeLibGuid (UCOMITypeLib pTLB)
641 throw new NotImplementedException ();
645 public static Guid GetTypeLibGuid (ITypeLib typelib)
647 throw new NotImplementedException ();
651 public static Guid GetTypeLibGuidForAssembly (Assembly asm)
653 throw new NotImplementedException ();
658 public static int GetTypeLibLcid (UCOMITypeLib pTLB)
660 throw new NotImplementedException ();
664 public static int GetTypeLibLcid (ITypeLib typelib)
666 throw new NotImplementedException ();
671 public static string GetTypeLibName (UCOMITypeLib pTLB)
673 throw new NotImplementedException ();
677 public static string GetTypeLibName (ITypeLib typelib)
679 throw new NotImplementedException ();
683 public static void GetTypeLibVersionForAssembly (Assembly inputAssembly, out int majorVersion, out int minorVersion)
685 throw new NotImplementedException ();
689 [Obsolete ("This method has been deprecated")]
690 public static IntPtr GetUnmanagedThunkForManagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
692 throw new NotImplementedException ();
696 public static bool IsTypeVisibleFromCom (Type t)
698 throw new NotImplementedException ();
702 public static int NumParamBytes (MethodInfo m)
704 throw new NotImplementedException ();
706 #endif // !FULL_AOT_RUNTIME
708 public static Type GetTypeFromCLSID (Guid clsid)
710 throw new PlatformNotSupportedException ();
713 public static string GetTypeInfoName (ITypeInfo typeInfo)
715 throw new PlatformNotSupportedException ();
718 public static object GetUniqueObjectForIUnknown (IntPtr unknown)
720 throw new PlatformNotSupportedException ();
724 [MethodImplAttribute (MethodImplOptions.InternalCall)]
725 public extern static bool IsComObject (object o);
727 public static bool IsComObject (object o)
729 throw new PlatformNotSupportedException ();
733 [MethodImplAttribute(MethodImplOptions.InternalCall)]
734 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
735 public static extern int GetLastWin32Error();
737 [MethodImplAttribute(MethodImplOptions.InternalCall)]
738 public extern static IntPtr OffsetOf (Type t, string fieldName);
740 public static IntPtr OffsetOf<T> (string fieldName) {
741 return OffsetOf (typeof (T), fieldName);
744 [MethodImplAttribute(MethodImplOptions.InternalCall)]
745 public extern static void Prelink (MethodInfo m);
747 [MethodImplAttribute(MethodImplOptions.InternalCall)]
748 public extern static void PrelinkAll (Type c);
750 [MethodImplAttribute(MethodImplOptions.InternalCall)]
751 public extern static string PtrToStringAnsi (IntPtr ptr);
753 [MethodImplAttribute(MethodImplOptions.InternalCall)]
754 public extern static string PtrToStringAnsi (IntPtr ptr, int len);
756 public static string PtrToStringAuto (IntPtr ptr)
758 return SystemDefaultCharSize == 2
759 ? PtrToStringUni (ptr) : PtrToStringAnsi (ptr);
762 public static string PtrToStringAuto (IntPtr ptr, int len)
764 return SystemDefaultCharSize == 2
765 ? PtrToStringUni (ptr, len) : PtrToStringAnsi (ptr, len);
768 [MethodImplAttribute(MethodImplOptions.InternalCall)]
769 public extern static string PtrToStringUni (IntPtr ptr);
771 [MethodImplAttribute(MethodImplOptions.InternalCall)]
772 public extern static string PtrToStringUni (IntPtr ptr, int len);
775 [MethodImplAttribute(MethodImplOptions.InternalCall)]
776 public extern static string PtrToStringBSTR (IntPtr ptr);
778 public static string PtrToStringBSTR (IntPtr ptr)
780 throw new NotImplementedException ();
784 [MethodImplAttribute(MethodImplOptions.InternalCall)]
786 public extern static void PtrToStructure (IntPtr ptr, object structure);
788 [MethodImplAttribute(MethodImplOptions.InternalCall)]
790 public extern static object PtrToStructure (IntPtr ptr, Type structureType);
792 public static void PtrToStructure<T> (IntPtr ptr, T structure) {
793 PtrToStructure (ptr, (object)structure);
796 public static T PtrToStructure<T> (IntPtr ptr) {
797 return (T) PtrToStructure (ptr, typeof (T));
801 [MethodImplAttribute (MethodImplOptions.InternalCall)]
802 private extern static int QueryInterfaceInternal (IntPtr pUnk, ref Guid iid, out IntPtr ppv);
805 public static int QueryInterface (IntPtr pUnk, ref Guid iid, out IntPtr ppv)
808 if (pUnk == IntPtr.Zero)
809 throw new ArgumentException ("Value cannot be null.", "pUnk");
810 return QueryInterfaceInternal (pUnk, ref iid, out ppv);
812 throw new NotImplementedException ();
816 public static byte ReadByte (IntPtr ptr)
823 public static byte ReadByte (IntPtr ptr, int ofs) {
825 return *((byte*)ptr + ofs);
830 [SuppressUnmanagedCodeSecurity]
831 public static byte ReadByte ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
833 throw new NotImplementedException ();
836 public unsafe static short ReadInt16 (IntPtr ptr)
838 byte *addr = (byte *) ptr;
840 // The mono JIT can't inline this due to the hight number of calls
841 // return ReadInt16 (ptr, 0);
843 if (((uint)addr & 1) == 0)
844 return *(short*)addr;
847 Buffer.Memcpy ((byte*)&s, (byte*)ptr, 2);
851 public unsafe static short ReadInt16 (IntPtr ptr, int ofs)
853 byte *addr = ((byte *) ptr) + ofs;
855 if (((uint) addr & 1) == 0)
856 return *(short*)addr;
859 Buffer.Memcpy ((byte*)&s, addr, 2);
864 [SuppressUnmanagedCodeSecurity]
865 public static short ReadInt16 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
867 throw new NotImplementedException ();
870 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
871 public unsafe static int ReadInt32 (IntPtr ptr)
873 byte *addr = (byte *) ptr;
875 if (((uint)addr & 3) == 0)
879 Buffer.Memcpy ((byte*)&s, addr, 4);
883 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
884 public unsafe static int ReadInt32 (IntPtr ptr, int ofs)
886 byte *addr = ((byte *) ptr) + ofs;
888 if ((((int) addr) & 3) == 0)
892 Buffer.Memcpy ((byte*)&s, addr, 4);
897 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
899 [SuppressUnmanagedCodeSecurity]
900 public static int ReadInt32 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
902 throw new NotImplementedException ();
905 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
906 public unsafe static long ReadInt64 (IntPtr ptr)
908 byte *addr = (byte *) ptr;
910 // The real alignment might be 4 on some platforms, but this is just an optimization,
911 // so it doesn't matter.
912 if (((uint) addr & 7) == 0)
916 Buffer.Memcpy ((byte*)&s, addr, 8);
920 public unsafe static long ReadInt64 (IntPtr ptr, int ofs)
922 byte *addr = ((byte *) ptr) + ofs;
924 if (((uint) addr & 7) == 0)
928 Buffer.Memcpy ((byte*)&s, addr, 8);
932 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
934 [SuppressUnmanagedCodeSecurity]
935 public static long ReadInt64 ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
937 throw new NotImplementedException ();
940 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
941 public static IntPtr ReadIntPtr (IntPtr ptr)
943 if (IntPtr.Size == 4)
944 return (IntPtr)ReadInt32 (ptr);
946 return (IntPtr)ReadInt64 (ptr);
949 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
950 public static IntPtr ReadIntPtr (IntPtr ptr, int ofs)
952 if (IntPtr.Size == 4)
953 return (IntPtr)ReadInt32 (ptr, ofs);
955 return (IntPtr)ReadInt64 (ptr, ofs);
958 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
960 public static IntPtr ReadIntPtr ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
962 throw new NotImplementedException ();
965 [MethodImplAttribute (MethodImplOptions.InternalCall)]
966 public extern static IntPtr ReAllocCoTaskMem (IntPtr pv, int cb);
968 [MethodImplAttribute(MethodImplOptions.InternalCall)]
969 public extern static IntPtr ReAllocHGlobal (IntPtr pv, IntPtr cb);
972 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
973 [MethodImplAttribute (MethodImplOptions.InternalCall)]
974 private extern static int ReleaseInternal (IntPtr pUnk);
977 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
978 public static int Release (IntPtr pUnk)
981 if (pUnk == IntPtr.Zero)
982 throw new ArgumentException ("Value cannot be null.", "pUnk");
984 return ReleaseInternal (pUnk);
986 throw new NotImplementedException ();
990 #if !FULL_AOT_RUNTIME
991 [MethodImplAttribute (MethodImplOptions.InternalCall)]
992 private extern static int ReleaseComObjectInternal (object co);
995 public static int ReleaseComObject (object o)
998 throw new PlatformNotSupportedException ();
1001 throw new ArgumentException ("Value cannot be null.", "o");
1002 if (!IsComObject (o))
1003 throw new ArgumentException ("Value must be a Com object.", "o");
1004 return ReleaseComObjectInternal (o);
1008 #if !FULL_AOT_RUNTIME
1011 public static void ReleaseThreadCache()
1013 throw new NotImplementedException ();
1016 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
1017 public static bool SetComObjectData (object obj, object key, object data)
1019 throw new NotSupportedException ("MSDN states user code should never need to call this method.");
1024 public static int SizeOf (object structure)
1026 return SizeOf (structure.GetType ());
1029 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1030 public extern static int SizeOf (Type t);
1032 public static int SizeOf<T> () {
1033 return SizeOf (typeof (T));
1036 public static int SizeOf<T> (T structure) {
1037 return SizeOf (structure.GetType ());
1040 internal static uint SizeOfType (Type type)
1042 return (uint) SizeOf (type);
1045 internal static uint AlignedSizeOf<T> () where T : struct
1047 uint size = SizeOfType (typeof (T));
1048 if (size == 1 || size == 2)
1050 if (IntPtr.Size == 8 && size == 4)
1052 return (size + 3) & (~((uint)3));
1055 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1056 public extern static IntPtr StringToBSTR (string s);
1059 // I believe this is wrong, because in Mono and in P/Invoke
1060 // we treat "Ansi" conversions as UTF-8 conversions, while
1061 // this one does not do this
1063 public static IntPtr StringToCoTaskMemAnsi (string s)
1065 int length = s.Length + 1;
1066 IntPtr ctm = AllocCoTaskMem (length);
1068 byte[] asBytes = new byte[length];
1069 for (int i = 0; i < s.Length; i++)
1070 asBytes[i] = (byte)s[i];
1071 asBytes[s.Length] = 0;
1073 copy_to_unmanaged (asBytes, 0, ctm, length);
1077 public static IntPtr StringToCoTaskMemAuto (string s)
1079 return SystemDefaultCharSize == 2
1080 ? StringToCoTaskMemUni (s) : StringToCoTaskMemAnsi (s);
1083 public static IntPtr StringToCoTaskMemUni (string s)
1085 int length = s.Length + 1;
1086 IntPtr ctm = AllocCoTaskMem (length * 2);
1088 char[] asChars = new char[length];
1089 s.CopyTo (0, asChars, 0, s.Length);
1090 asChars[s.Length] = '\0';
1092 copy_to_unmanaged (asChars, 0, ctm, length);
1096 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1097 public extern static IntPtr StringToHGlobalAnsi (string s);
1099 public static IntPtr StringToHGlobalAuto (string s)
1101 return SystemDefaultCharSize == 2
1102 ? StringToHGlobalUni (s) : StringToHGlobalAnsi (s);
1105 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1106 public extern static IntPtr StringToHGlobalUni (string s);
1108 public static IntPtr SecureStringToBSTR (SecureString s)
1111 throw new ArgumentNullException ("s");
1113 byte[] buffer = s.GetBuffer ();
1116 // SecureString doesn't take endian-ness into account.
1117 // Therefore swap bytes here before we send it to c-side if little-endian.
1118 if (BitConverter.IsLittleEndian) {
1119 for (int i = 0; i < buffer.Length; i += 2) {
1121 buffer[i] = buffer[i + 1];
1125 return BufferToBSTR (buffer, len);
1128 public static IntPtr SecureStringToCoTaskMemAnsi (SecureString s)
1131 throw new ArgumentNullException ("s");
1133 IntPtr ctm = AllocCoTaskMem (len + 1);
1134 byte [] copy = new byte [len+1];
1137 byte [] buffer = s.GetBuffer ();
1139 for (; i < len; i++, j += 2){
1140 copy [i] = buffer [j+1];
1145 copy_to_unmanaged (copy, 0, ctm, len+1);
1147 // Ensure that we clear the buffer.
1148 for (int i = len; i > 0; ){
1156 public static IntPtr SecureStringToCoTaskMemUnicode (SecureString s)
1159 throw new ArgumentNullException ("s");
1161 IntPtr ctm = AllocCoTaskMem (len * 2 + 2);
1162 byte [] buffer = null;
1164 buffer = s.GetBuffer ();
1165 for (int i = 0; i < len; i++)
1166 WriteInt16 (ctm, i * 2, (short) ((buffer [(i*2)] << 8) | (buffer [i*2+1])));
1167 WriteInt16 (ctm, buffer.Length, 0);
1170 for (int i = buffer.Length; i > 0; ){
1178 public static IntPtr SecureStringToGlobalAllocAnsi (SecureString s)
1181 throw new ArgumentNullException ("s");
1182 return SecureStringToCoTaskMemAnsi (s);
1185 public static IntPtr SecureStringToGlobalAllocUnicode (SecureString s)
1188 throw new ArgumentNullException ("s");
1189 return SecureStringToCoTaskMemUnicode (s);
1192 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
1194 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1195 public extern static void StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld);
1197 public static void StructureToPtr<T> (T structure, IntPtr ptr, bool fDeleteOld) {
1198 StructureToPtr ((object)structure, ptr, fDeleteOld);
1201 public static void ThrowExceptionForHR (int errorCode) {
1202 Exception ex = GetExceptionForHR (errorCode);
1207 public static void ThrowExceptionForHR (int errorCode, IntPtr errorInfo) {
1208 Exception ex = GetExceptionForHR (errorCode, errorInfo);
1214 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1215 public extern static IntPtr BufferToBSTR (Array ptr, int slen);
1217 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1218 public extern static IntPtr UnsafeAddrOfPinnedArrayElement (Array arr, int index);
1220 public static IntPtr UnsafeAddrOfPinnedArrayElement<T> (T[] arr, int index) {
1221 return UnsafeAddrOfPinnedArrayElement ((Array)arr, index);
1224 public static void WriteByte (IntPtr ptr, byte val)
1231 public static void WriteByte (IntPtr ptr, int ofs, byte val) {
1233 *(byte*)(IntPtr.Add (ptr, ofs)) = val;
1238 [SuppressUnmanagedCodeSecurity]
1239 public static void WriteByte ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, byte val)
1241 throw new NotImplementedException ();
1244 public static unsafe void WriteInt16 (IntPtr ptr, short val)
1246 byte *addr = (byte *) ptr;
1248 if (((uint)addr & 1) == 0)
1249 *(short*)addr = val;
1251 Buffer.Memcpy (addr, (byte*)&val, 2);
1254 public static unsafe void WriteInt16 (IntPtr ptr, int ofs, short val)
1256 byte *addr = ((byte *) ptr) + ofs;
1258 if (((uint)addr & 1) == 0)
1259 *(short*)addr = val;
1261 Buffer.Memcpy (addr, (byte*)&val, 2);
1266 [SuppressUnmanagedCodeSecurity]
1267 public static void WriteInt16 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, short val)
1269 throw new NotImplementedException ();
1272 public static void WriteInt16 (IntPtr ptr, char val)
1274 WriteInt16 (ptr, 0, (short)val);
1277 public static void WriteInt16 (IntPtr ptr, int ofs, char val)
1279 WriteInt16 (ptr, ofs, (short)val);
1283 public static void WriteInt16([In, Out] object ptr, int ofs, char val)
1285 throw new NotImplementedException ();
1288 public static unsafe void WriteInt32 (IntPtr ptr, int val)
1290 byte *addr = (byte *) ptr;
1292 if (((uint)addr & 3) == 0)
1295 Buffer.Memcpy (addr, (byte*)&val, 4);
1299 public unsafe static void WriteInt32 (IntPtr ptr, int ofs, int val)
1301 byte *addr = ((byte *) ptr) + ofs;
1303 if (((uint)addr & 3) == 0)
1306 Buffer.Memcpy (addr, (byte*)&val, 4);
1311 [SuppressUnmanagedCodeSecurity]
1312 public static void WriteInt32([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, int val)
1314 throw new NotImplementedException ();
1317 public static unsafe void WriteInt64 (IntPtr ptr, long val)
1319 byte *addr = (byte *) ptr;
1321 // The real alignment might be 4 on some platforms, but this is just an optimization,
1322 // so it doesn't matter.
1323 if (((uint)addr & 7) == 0)
1326 Buffer.Memcpy (addr, (byte*)&val, 8);
1329 public static unsafe void WriteInt64 (IntPtr ptr, int ofs, long val)
1331 byte *addr = ((byte *) ptr) + ofs;
1333 // The real alignment might be 4 on some platforms, but this is just an optimization,
1334 // so it doesn't matter.
1335 if (((uint)addr & 7) == 0)
1338 Buffer.Memcpy (addr, (byte*)&val, 8);
1342 [SuppressUnmanagedCodeSecurity]
1343 public static void WriteInt64 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, long val)
1345 throw new NotImplementedException ();
1348 public static void WriteIntPtr (IntPtr ptr, IntPtr val)
1350 if (IntPtr.Size == 4)
1351 WriteInt32 (ptr, (int)val);
1353 WriteInt64 (ptr, (long)val);
1356 public static void WriteIntPtr (IntPtr ptr, int ofs, IntPtr val)
1358 if (IntPtr.Size == 4)
1359 WriteInt32 (ptr, ofs, (int)val);
1361 WriteInt64 (ptr, ofs, (long)val);
1365 public static void WriteIntPtr([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, IntPtr val)
1367 throw new NotImplementedException ();
1370 private static Exception ConvertHrToException (int errorCode)
1372 const int MSEE_E_APPDOMAINUNLOADED = unchecked ((int)0x80131014L);
1373 const int COR_E_APPLICATION = unchecked ((int)0x80131600L);
1374 const int E_INVALIDARG = unchecked ((int)0x80070057);
1375 const int COR_E_ARGUMENTOUTOFRANGE = unchecked ((int)0x80131502L);
1376 const int COR_E_ARITHMETIC = unchecked ((int)0x80070216);
1377 const int COR_E_ARRAYTYPEMISMATCH = unchecked ((int)0x80131503L);
1378 const int COR_E_BADIMAGEFORMAT = unchecked ((int)0x8007000BL);
1379 const int ERROR_BAD_FORMAT = unchecked ((int)0x0B);
1380 //const int COR_E_COMEMULATE_ERROR = unchecked ((int)?);
1381 const int COR_E_CONTEXTMARSHAL = unchecked ((int)0x80131504L);
1382 //const int COR_E_CORE = unchecked ((int)?);
1383 const int NTE_FAIL = unchecked ((int)0x80090020L);
1384 const int COR_E_DIRECTORYNOTFOUND = unchecked ((int)0x80070003L);
1385 const int ERROR_PATH_NOT_FOUND = unchecked ((int)0x03);
1386 const int COR_E_DIVIDEBYZERO = unchecked ((int)0x80020012L);
1387 const int COR_E_DUPLICATEWAITOBJECT = unchecked ((int)0x80131529L);
1388 const int COR_E_ENDOFSTREAM = unchecked ((int)0x80070026L);
1389 const int COR_E_TYPELOAD = unchecked ((int)0x80131522L);
1390 const int COR_E_EXCEPTION = unchecked ((int)0x80131500L);
1391 const int COR_E_EXECUTIONENGINE = unchecked ((int)0x80131506L);
1392 const int COR_E_FIELDACCESS = unchecked ((int)0x80131507L);
1393 const int COR_E_FILENOTFOUND = unchecked ((int)0x80070002L);
1394 const int ERROR_FILE_NOT_FOUND = unchecked ((int)0x02);
1395 const int COR_E_FORMAT = unchecked ((int)0x80131537L);
1396 const int COR_E_INDEXOUTOFRANGE = unchecked ((int)0x80131508L);
1397 const int COR_E_INVALIDCAST = unchecked ((int)0x80004002L);
1398 const int COR_E_INVALIDCOMOBJECT = unchecked ((int)0x80131527L);
1399 const int COR_E_INVALIDFILTERCRITERIA = unchecked ((int)0x80131601L);
1400 const int COR_E_INVALIDOLEVARIANTTYPE = unchecked ((int)0x80131531L);
1401 const int COR_E_INVALIDOPERATION = unchecked ((int)0x80131509L);
1402 const int COR_E_IO = unchecked ((int)0x80131620L);
1403 const int COR_E_MEMBERACCESS = unchecked ((int)0x8013151AL);
1404 const int COR_E_METHODACCESS = unchecked ((int)0x80131510L);
1405 const int COR_E_MISSINGFIELD = unchecked ((int)0x80131511L);
1406 const int COR_E_MISSINGMANIFESTRESOURCE = unchecked ((int)0x80131532L);
1407 const int COR_E_MISSINGMEMBER = unchecked ((int)0x80131512L);
1408 const int COR_E_MISSINGMETHOD = unchecked ((int)0x80131513L);
1409 const int COR_E_MULTICASTNOTSUPPORTED = unchecked ((int)0x80131514L);
1410 const int COR_E_NOTFINITENUMBER = unchecked ((int)0x80131528L);
1411 const int E_NOTIMPL = unchecked ((int)0x80004001L);
1412 const int COR_E_NOTSUPPORTED = unchecked ((int)0x80131515L);
1413 const int COR_E_NULLREFERENCE = unchecked ((int)0x80004003L);
1414 const int E_OUTOFMEMORY = unchecked ((int)0x8007000EL);
1415 const int COR_E_OVERFLOW = unchecked ((int)0x80131516L);
1416 const int COR_E_PATHTOOLONG = unchecked ((int)0x800700CEL);
1417 const int ERROR_FILENAME_EXCED_RANGE = unchecked ((int)0xCE);
1418 const int COR_E_RANK = unchecked ((int)0x80131517L);
1419 const int COR_E_REFLECTIONTYPELOAD = unchecked ((int)0x80131602L);
1420 const int COR_E_REMOTING = unchecked ((int)0x8013150BL);
1421 const int COR_E_SAFEARRAYTYPEMISMATCH = unchecked ((int)0x80131533L);
1422 const int COR_E_SECURITY = unchecked ((int)0x8013150AL);
1423 const int COR_E_SERIALIZATION = unchecked ((int)0x8013150CL);
1424 const int COR_E_STACKOVERFLOW = unchecked ((int)0x800703E9L);
1425 const int ERROR_STACK_OVERFLOW = unchecked ((int)0x03E9);
1426 const int COR_E_SYNCHRONIZATIONLOCK = unchecked ((int)0x80131518L);
1427 const int COR_E_SYSTEM = unchecked ((int)0x80131501L);
1428 const int COR_E_TARGET = unchecked ((int)0x80131603L);
1429 const int COR_E_TARGETINVOCATION = unchecked ((int)0x80131604L);
1430 const int COR_E_TARGETPARAMCOUNT = unchecked ((int)0x8002000EL);
1431 const int COR_E_THREADABORTED = unchecked ((int)0x80131530L);
1432 const int COR_E_THREADINTERRUPTED = unchecked ((int)0x80131519L);
1433 const int COR_E_THREADSTATE = unchecked ((int)0x80131520L);
1434 const int COR_E_THREADSTOP = unchecked ((int)0x80131521L);
1435 const int COR_E_TYPEINITIALIZATION = unchecked ((int)0x80131534L);
1436 const int COR_E_VERIFICATION = unchecked ((int)0x8013150DL);
1437 //const int COR_E_WEAKREFERENCE = unchecked ((int)?);
1438 //const int COR_E_VTABLECALLSNOTSUPPORTED = unchecked ((int));
1440 switch (errorCode) {
1441 case MSEE_E_APPDOMAINUNLOADED:
1442 return new AppDomainUnloadedException ();
1443 case COR_E_APPLICATION:
1444 return new ApplicationException ();
1446 return new ArgumentException ();
1447 case COR_E_ARGUMENTOUTOFRANGE:
1448 return new ArgumentOutOfRangeException ();
1449 case COR_E_ARITHMETIC:
1450 return new ArithmeticException ();
1451 case COR_E_ARRAYTYPEMISMATCH:
1452 return new ArrayTypeMismatchException ();
1453 case COR_E_BADIMAGEFORMAT:
1454 case ERROR_BAD_FORMAT:
1455 return new BadImageFormatException ();
1456 // case COR_E_COMEMULATE_ERROR:
1457 // return new COMEmulateException ();
1458 case COR_E_CONTEXTMARSHAL:
1459 return new ContextMarshalException ();
1461 // return new CoreException ();
1463 return new System.Security.Cryptography.CryptographicException ();
1464 case COR_E_DIRECTORYNOTFOUND:
1465 case ERROR_PATH_NOT_FOUND:
1466 return new System.IO.DirectoryNotFoundException ();
1467 case COR_E_DIVIDEBYZERO:
1468 return new DivideByZeroException ();
1469 case COR_E_DUPLICATEWAITOBJECT:
1470 return new DuplicateWaitObjectException ();
1471 case COR_E_ENDOFSTREAM:
1472 return new System.IO.EndOfStreamException ();
1473 case COR_E_EXCEPTION:
1474 return new Exception ();
1475 case COR_E_EXECUTIONENGINE:
1476 return new ExecutionEngineException ();
1477 case COR_E_FIELDACCESS:
1478 return new FieldAccessException ();
1479 case COR_E_FILENOTFOUND:
1480 case ERROR_FILE_NOT_FOUND:
1481 return new System.IO.FileNotFoundException ();
1483 return new FormatException ();
1484 case COR_E_INDEXOUTOFRANGE:
1485 return new IndexOutOfRangeException ();
1486 case COR_E_INVALIDCAST:
1487 // E_NOINTERFACE has same value as COR_E_INVALIDCAST
1488 return new InvalidCastException ();
1489 case COR_E_INVALIDCOMOBJECT:
1490 return new InvalidComObjectException ();
1491 case COR_E_INVALIDFILTERCRITERIA:
1492 return new InvalidFilterCriteriaException ();
1493 case COR_E_INVALIDOLEVARIANTTYPE:
1494 return new InvalidOleVariantTypeException ();
1495 case COR_E_INVALIDOPERATION:
1496 return new InvalidOperationException ();
1498 return new System.IO.IOException ();
1499 case COR_E_MEMBERACCESS:
1500 return new MemberAccessException ();
1501 case COR_E_METHODACCESS:
1502 return new MethodAccessException ();
1503 case COR_E_MISSINGFIELD:
1504 return new MissingFieldException ();
1505 case COR_E_MISSINGMANIFESTRESOURCE:
1506 return new System.Resources.MissingManifestResourceException ();
1507 case COR_E_MISSINGMEMBER:
1508 return new MissingMemberException ();
1509 case COR_E_MISSINGMETHOD:
1510 return new MissingMethodException ();
1511 case COR_E_MULTICASTNOTSUPPORTED:
1512 return new MulticastNotSupportedException ();
1513 case COR_E_NOTFINITENUMBER:
1514 return new NotFiniteNumberException ();
1516 return new NotImplementedException ();
1517 case COR_E_NOTSUPPORTED:
1518 return new NotSupportedException ();
1519 case COR_E_NULLREFERENCE:
1520 // E_POINTER has the same value as COR_E_NULLREFERENCE
1521 return new NullReferenceException ();
1523 // COR_E_OUTOFMEMORY has the same value as E_OUTOFMEMORY
1524 return new OutOfMemoryException ();
1525 case COR_E_OVERFLOW:
1526 return new OverflowException ();
1527 case COR_E_PATHTOOLONG:
1528 case ERROR_FILENAME_EXCED_RANGE:
1529 return new System.IO.PathTooLongException ();
1531 return new RankException ();
1532 case COR_E_REFLECTIONTYPELOAD:
1533 return new System.Reflection.ReflectionTypeLoadException (new Type[] { }, new Exception[] { });
1534 case COR_E_REMOTING:
1535 return new System.Runtime.Remoting.RemotingException ();
1536 case COR_E_SAFEARRAYTYPEMISMATCH:
1537 return new SafeArrayTypeMismatchException ();
1538 case COR_E_SECURITY:
1539 return new SecurityException ();
1540 case COR_E_SERIALIZATION:
1541 return new System.Runtime.Serialization.SerializationException ();
1542 case COR_E_STACKOVERFLOW:
1543 case ERROR_STACK_OVERFLOW:
1544 return new StackOverflowException ();
1545 case COR_E_SYNCHRONIZATIONLOCK:
1546 return new SynchronizationLockException ();
1548 return new SystemException ();
1550 return new TargetException ();
1551 case COR_E_TARGETINVOCATION:
1552 return new System.Reflection.TargetInvocationException (null);
1553 case COR_E_TARGETPARAMCOUNT:
1554 return new TargetParameterCountException ();
1555 // case COR_E_THREADABORTED:
1556 // ThreadAbortException c'tor is inaccessible
1557 // return new System.Threading.ThreadAbortException ();
1558 case COR_E_THREADINTERRUPTED:
1559 return new ThreadInterruptedException ();
1560 case COR_E_THREADSTATE:
1561 return new ThreadStateException ();
1562 // case COR_E_THREADSTOP:
1563 // ThreadStopException does not exist
1564 // return new System.Threading.ThreadStopException ();
1565 case COR_E_TYPELOAD:
1566 return new TypeLoadException ();
1567 // MSDN lists COR_E_TYPELOAD twice with different exceptions.
1568 // return new EntryPointNotFoundException ();
1569 case COR_E_TYPEINITIALIZATION:
1570 return new TypeInitializationException("", null);
1571 case COR_E_VERIFICATION:
1572 return new VerificationException ();
1573 // case COR_E_WEAKREFERENCE:
1574 // return new WeakReferenceException ();
1575 // case COR_E_VTABLECALLSNOTSUPPORTED:
1576 // return new VTableCallsNotSupportedException ();
1579 return new COMException ("", errorCode);
1583 #if FEATURE_COMINTEROP
1584 [DllImport ("oleaut32.dll", CharSet=CharSet.Unicode, EntryPoint = "SetErrorInfo")]
1585 static extern int _SetErrorInfo (int dwReserved,
1586 [MarshalAs(UnmanagedType.Interface)] IErrorInfo pIErrorInfo);
1588 [DllImport ("oleaut32.dll", CharSet=CharSet.Unicode, EntryPoint = "GetErrorInfo")]
1589 static extern int _GetErrorInfo (int dwReserved,
1590 [MarshalAs(UnmanagedType.Interface)] out IErrorInfo ppIErrorInfo);
1592 static bool SetErrorInfoNotAvailable;
1593 static bool GetErrorInfoNotAvailable;
1595 internal static int SetErrorInfo (int dwReserved, IErrorInfo errorInfo)
1600 if (SetErrorInfoNotAvailable)
1604 retVal = _SetErrorInfo (dwReserved, errorInfo);
1607 // ignore any exception - probably there's no suitable SetErrorInfo
1608 // method available.
1609 SetErrorInfoNotAvailable = true;
1614 internal static int GetErrorInfo (int dwReserved, out IErrorInfo errorInfo)
1619 if (GetErrorInfoNotAvailable)
1623 retVal = _GetErrorInfo (dwReserved, out errorInfo);
1626 // ignore any exception - probably there's no suitable GetErrorInfo
1627 // method available.
1628 GetErrorInfoNotAvailable = true;
1633 public static Exception GetExceptionForHR (int errorCode)
1635 return GetExceptionForHR (errorCode, IntPtr.Zero);
1638 public static Exception GetExceptionForHR (int errorCode, IntPtr errorInfo)
1640 #if FEATURE_COMINTEROP
1641 IErrorInfo info = null;
1642 if (errorInfo != (IntPtr)(-1)) {
1643 if (errorInfo == IntPtr.Zero) {
1644 if (GetErrorInfo (0, out info) != 0) {
1648 info = Marshal.GetObjectForIUnknown (errorInfo) as IErrorInfo;
1652 if (info is ManagedErrorInfo && ((ManagedErrorInfo) info).Exception._HResult == errorCode) {
1653 return ((ManagedErrorInfo) info).Exception;
1656 Exception e = ConvertHrToException (errorCode);
1657 if (info != null && e != null) {
1659 info.GetHelpContext (out helpContext);
1661 info.GetSource (out str);
1663 info.GetDescription (out str);
1665 info.GetHelpFile (out str);
1667 if (helpContext == 0) {
1670 e.HelpLink = string.Format ("{0}#{1}", str, helpContext);
1675 return ConvertHrToException (errorCode);
1679 public static int FinalReleaseComObject (object o)
1681 while (ReleaseComObject (o) != 0);
1685 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1686 private static extern Delegate GetDelegateForFunctionPointerInternal (IntPtr ptr, Type t);
1688 public static Delegate GetDelegateForFunctionPointer (IntPtr ptr, Type t)
1691 throw new ArgumentNullException ("t");
1692 if (!t.IsSubclassOf (typeof (MulticastDelegate)) || (t == typeof (MulticastDelegate)))
1693 throw new ArgumentException ("Type is not a delegate", "t");
1694 if (t.IsGenericType)
1695 throw new ArgumentException ("The specified Type must not be a generic type definition.");
1696 if (ptr == IntPtr.Zero)
1697 throw new ArgumentNullException ("ptr");
1699 return GetDelegateForFunctionPointerInternal (ptr, t);
1702 public static TDelegate GetDelegateForFunctionPointer<TDelegate> (IntPtr ptr) {
1703 return (TDelegate) (object) GetDelegateForFunctionPointer (ptr, typeof (TDelegate));
1706 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1707 private static extern IntPtr GetFunctionPointerForDelegateInternal (Delegate d);
1709 public static IntPtr GetFunctionPointerForDelegate (Delegate d)
1712 throw new ArgumentNullException ("d");
1714 return GetFunctionPointerForDelegateInternal (d);
1717 public static IntPtr GetFunctionPointerForDelegate<TDelegate> (TDelegate d) {
1719 throw new ArgumentNullException ("d");
1721 return GetFunctionPointerForDelegateInternal ((Delegate)(object)d);
1724 internal static void SetLastWin32Error (int error)