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;
43 using System.Runtime.ConstrainedExecution;
48 namespace System.Runtime.InteropServices
50 public static class Marshal
53 public static readonly int SystemMaxDBCSCharSize = 2; // don't know what this is
54 public static readonly int SystemDefaultCharSize = Environment.IsRunningOnWindows ? 2 : 1;
57 [MethodImplAttribute (MethodImplOptions.InternalCall)]
58 private extern static int AddRefInternal (IntPtr pUnk);
61 public static int AddRef (IntPtr pUnk)
64 if (pUnk == IntPtr.Zero)
65 throw new ArgumentException ("Value cannot be null.", "pUnk");
66 return AddRefInternal (pUnk);
68 throw new NotImplementedException ();
73 public static bool AreComObjectsAvailableForCleanup ()
79 public static void CleanupUnusedObjectsInCurrentContext ()
81 if (Environment.IsRunningOnWindows)
82 throw new PlatformNotSupportedException ();
85 [MethodImplAttribute(MethodImplOptions.InternalCall)]
86 public extern static IntPtr AllocCoTaskMem (int cb);
88 [MethodImplAttribute(MethodImplOptions.InternalCall)]
89 internal extern static IntPtr AllocCoTaskMemSize (UIntPtr sizet);
91 [MethodImplAttribute(MethodImplOptions.InternalCall)]
92 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
93 public extern static IntPtr AllocHGlobal (IntPtr cb);
95 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
96 public static IntPtr AllocHGlobal (int cb)
98 return AllocHGlobal ((IntPtr)cb);
102 public static object BindToMoniker (string monikerName)
104 throw new NotImplementedException ();
108 public static void ChangeWrapperHandleStrength (object otp, bool fIsWeak)
110 throw new NotImplementedException ();
113 [MethodImplAttribute(MethodImplOptions.InternalCall)]
114 internal extern static void copy_to_unmanaged (Array source, int startIndex,
115 IntPtr destination, int length);
117 [MethodImplAttribute(MethodImplOptions.InternalCall)]
118 internal extern static void copy_from_unmanaged (IntPtr source, int startIndex,
119 Array destination, int length);
121 public static void Copy (byte[] source, int startIndex, IntPtr destination, int length)
123 copy_to_unmanaged (source, startIndex, destination, length);
126 public static void Copy (char[] source, int startIndex, IntPtr destination, int length)
128 copy_to_unmanaged (source, startIndex, destination, length);
131 public static void Copy (short[] source, int startIndex, IntPtr destination, int length)
133 copy_to_unmanaged (source, startIndex, destination, length);
136 public static void Copy (int[] source, int startIndex, IntPtr destination, int length)
138 copy_to_unmanaged (source, startIndex, destination, length);
141 public static void Copy (long[] source, int startIndex, IntPtr destination, int length)
143 copy_to_unmanaged (source, startIndex, destination, length);
146 public static void Copy (float[] source, int startIndex, IntPtr destination, int length)
148 copy_to_unmanaged (source, startIndex, destination, length);
151 public static void Copy (double[] source, int startIndex, IntPtr destination, int length)
153 copy_to_unmanaged (source, startIndex, destination, length);
156 public static void Copy (IntPtr[] source, int startIndex, IntPtr destination, int length)
158 copy_to_unmanaged (source, startIndex, destination, length);
161 public static void Copy (IntPtr source, byte[] destination, int startIndex, int length)
163 copy_from_unmanaged (source, startIndex, destination, length);
166 public static void Copy (IntPtr source, char[] destination, int startIndex, int length)
168 copy_from_unmanaged (source, startIndex, destination, length);
171 public static void Copy (IntPtr source, short[] destination, int startIndex, int length)
173 copy_from_unmanaged (source, startIndex, destination, length);
176 public static void Copy (IntPtr source, int[] destination, int startIndex, int length)
178 copy_from_unmanaged (source, startIndex, destination, length);
181 public static void Copy (IntPtr source, long[] destination, int startIndex, int length)
183 copy_from_unmanaged (source, startIndex, destination, length);
186 public static void Copy (IntPtr source, float[] destination, int startIndex, int length)
188 copy_from_unmanaged (source, startIndex, destination, length);
191 public static void Copy (IntPtr source, double[] destination, int startIndex, int length)
193 copy_from_unmanaged (source, startIndex, destination, length);
196 public static void Copy (IntPtr source, IntPtr[] destination, int startIndex, int length)
198 copy_from_unmanaged (source, startIndex, destination, length);
201 public static IntPtr CreateAggregatedObject (IntPtr pOuter,
204 throw new NotImplementedException ();
207 public static IntPtr CreateAggregatedObject<T> (IntPtr pOuter, T o) {
208 return CreateAggregatedObject (pOuter, (object)o);
211 public static object CreateWrapperOfType (object o, Type t)
214 throw new PlatformNotSupportedException ();
216 __ComObject co = o as __ComObject;
218 throw new ArgumentException ("o must derive from __ComObject", "o");
220 throw new ArgumentNullException ("t");
222 Type[] itfs = o.GetType ().GetInterfaces ();
223 foreach (Type itf in itfs) {
224 if (itf.IsImport && co.GetInterface (itf) == IntPtr.Zero)
225 throw new InvalidCastException ();
228 return ComInteropProxy.GetProxy (co.IUnknown, t).GetTransparentProxy ();
232 public static TWrapper CreateWrapperOfType<T, TWrapper> (T o) {
233 return (TWrapper)CreateWrapperOfType ((object)o, typeof (TWrapper));
236 [MethodImplAttribute(MethodImplOptions.InternalCall)]
238 public extern static void DestroyStructure (IntPtr ptr, Type structuretype);
240 public static void DestroyStructure<T> (IntPtr ptr) {
241 DestroyStructure (ptr, typeof (T));
244 [MethodImplAttribute(MethodImplOptions.InternalCall)]
245 public extern static void FreeBSTR (IntPtr ptr);
247 [MethodImplAttribute(MethodImplOptions.InternalCall)]
248 public extern static void FreeCoTaskMem (IntPtr ptr);
250 [MethodImplAttribute(MethodImplOptions.InternalCall)]
251 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
252 public extern static void FreeHGlobal (IntPtr hglobal);
254 static void ClearBSTR (IntPtr ptr)
256 int len = ReadInt32 (ptr, -4);
258 for (int i = 0; i < len; i++)
259 WriteByte (ptr, i, 0);
262 public static void ZeroFreeBSTR (IntPtr s)
268 static void ClearAnsi (IntPtr ptr)
270 for (int i = 0; ReadByte (ptr, i) != 0; i++)
271 WriteByte (ptr, i, 0);
274 static void ClearUnicode (IntPtr ptr)
276 for (int i = 0; ReadInt16 (ptr, i) != 0; i += 2)
277 WriteInt16 (ptr, i, 0);
280 public static void ZeroFreeCoTaskMemAnsi (IntPtr s)
286 public static void ZeroFreeCoTaskMemUnicode (IntPtr s)
292 public static void ZeroFreeCoTaskMemUTF8 (IntPtr s)
298 public static void ZeroFreeGlobalAllocAnsi (IntPtr s)
304 public static void ZeroFreeGlobalAllocUnicode (IntPtr s)
310 #if !FULL_AOT_RUNTIME
311 public static Guid GenerateGuidForType (Type type)
316 public static string GenerateProgIdForType (Type type)
318 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (type);
320 foreach (var a in attrs)
322 var dt = a.Constructor.DeclaringType;
323 string name = dt.Name;
324 if (name == "ProgIdAttribute")
326 var args = a.ConstructorArguments;
327 string text = a.ConstructorArguments[0].Value as string;
336 return type.FullName;
340 public static object GetActiveObject (string progID)
342 throw new NotImplementedException ();
346 [MethodImplAttribute (MethodImplOptions.InternalCall)]
347 private extern static IntPtr GetCCW (object o, Type T);
349 private static IntPtr GetComInterfaceForObjectInternal (object o, Type T)
352 return ((__ComObject)o).GetInterface (T);
354 return GetCCW (o, T);
357 #endif // !FULL_AOT_RUNTIME
359 public static IntPtr GetComInterfaceForObject (object o, Type T)
362 throw new PlatformNotSupportedException ();
364 IntPtr pItf = GetComInterfaceForObjectInternal (o, T);
371 public static IntPtr GetComInterfaceForObject (object o, Type T, CustomQueryInterfaceMode mode)
373 throw new NotImplementedException ();
376 public static IntPtr GetComInterfaceForObject<T, TInterface> (T o) {
377 return GetComInterfaceForObject ((object)o, typeof (T));
380 #if !FULL_AOT_RUNTIME
382 public static IntPtr GetComInterfaceForObjectInContext (object o, Type t)
384 throw new NotImplementedException ();
387 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
388 public static object GetComObjectData (object obj, object key)
390 throw new NotSupportedException ("MSDN states user code should never need to call this method.");
394 [MethodImplAttribute(MethodImplOptions.InternalCall)]
395 private extern static int GetComSlotForMethodInfoInternal (MemberInfo m);
398 public static int GetComSlotForMethodInfo (MemberInfo m)
402 throw new ArgumentNullException ("m");
403 if (!(m is MethodInfo))
404 throw new ArgumentException ("The MemberInfo must be an interface method.", "m");
405 if (!m.DeclaringType.IsInterface)
406 throw new ArgumentException ("The MemberInfo must be an interface method.", "m");
407 return GetComSlotForMethodInfoInternal (m);
409 throw new NotImplementedException ();
414 public static int GetEndComSlot (Type t)
416 throw new NotImplementedException ();
421 public static IntPtr GetExceptionPointers()
423 throw new NotImplementedException ();
426 public static IntPtr GetHINSTANCE (Module m)
429 throw new ArgumentNullException ("m");
431 return m.GetHINSTANCE ();
433 #endif // !FULL_AOT_RUNTIME
435 public static int GetExceptionCode ()
437 throw new PlatformNotSupportedException ();
440 public static int GetHRForException (Exception e)
442 if (e == null) return 0;
444 #if FEATURE_COMINTEROP
445 var errorInfo = new ManagedErrorInfo(e);
446 SetErrorInfo (0, errorInfo);
453 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
454 public static int GetHRForLastWin32Error()
457 throw new PlatformNotSupportedException ();
459 throw new NotImplementedException ();
463 #if !FULL_AOT_RUNTIME
464 [MethodImplAttribute (MethodImplOptions.InternalCall)]
465 private extern static IntPtr GetIDispatchForObjectInternal (object o);
467 public static IntPtr GetIDispatchForObject (object o)
469 IntPtr pUnk = GetIDispatchForObjectInternal (o);
470 // Internal method does not AddRef
476 public static IntPtr GetIDispatchForObjectInContext (object o)
478 throw new NotImplementedException ();
482 public static IntPtr GetITypeInfoForType (Type t)
484 throw new NotImplementedException ();
488 public static IntPtr GetIUnknownForObjectInContext (object o)
490 throw new NotImplementedException ();
494 [Obsolete ("This method has been deprecated")]
495 public static IntPtr GetManagedThunkForUnmanagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
497 throw new NotImplementedException ();
501 public static MemberInfo GetMethodInfoForComSlot (Type t, int slot, ref ComMemberType memberType)
503 throw new NotImplementedException ();
506 [MethodImplAttribute (MethodImplOptions.InternalCall)]
507 private extern static IntPtr GetIUnknownForObjectInternal (object o);
509 #endif // !FULL_AOT_RUNTIME
511 public static IntPtr GetIUnknownForObject (object o)
514 throw new PlatformNotSupportedException ();
516 IntPtr pUnk = GetIUnknownForObjectInternal (o);
517 // Internal method does not AddRef
523 public static void GetNativeVariantForObject (object obj, IntPtr pDstNativeVariant)
526 throw new PlatformNotSupportedException ();
528 Variant vt = new Variant();
530 Marshal.StructureToPtr(vt, pDstNativeVariant, false);
534 public static void GetNativeVariantForObject<T> (T obj, IntPtr pDstNativeVariant) {
535 GetNativeVariantForObject ((object)obj, pDstNativeVariant);
538 #if !MOBILE && !FULL_AOT_RUNTIME
539 [MethodImplAttribute (MethodImplOptions.InternalCall)]
540 private static extern object GetObjectForCCW (IntPtr pUnk);
543 public static object GetObjectForIUnknown (IntPtr pUnk)
545 #if MOBILE || FULL_AOT_RUNTIME
546 throw new PlatformNotSupportedException ();
548 object obj = GetObjectForCCW (pUnk);
551 ComInteropProxy proxy = ComInteropProxy.GetProxy (pUnk, typeof (__ComObject));
552 obj = proxy.GetTransparentProxy ();
558 public static object GetObjectForNativeVariant (IntPtr pSrcNativeVariant)
561 throw new PlatformNotSupportedException ();
563 Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
564 return vt.GetValue();
568 public static T GetObjectForNativeVariant<T> (IntPtr pSrcNativeVariant)
571 throw new PlatformNotSupportedException ();
573 Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
574 return (T)vt.GetValue();
578 public static object[] GetObjectsForNativeVariants (IntPtr aSrcNativeVariant, int cVars)
581 throw new PlatformNotSupportedException ();
584 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
585 object[] objects = new object[cVars];
586 for (int i = 0; i < cVars; i++)
587 objects[i] = GetObjectForNativeVariant ((IntPtr)(aSrcNativeVariant.ToInt64 () +
588 i * SizeOf (typeof(Variant))));
593 public static T[] GetObjectsForNativeVariants<T> (IntPtr aSrcNativeVariant, int cVars)
596 throw new PlatformNotSupportedException ();
599 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
600 T[] objects = new T[cVars];
601 for (int i = 0; i < cVars; i++)
602 objects[i] = GetObjectForNativeVariant<T> ((IntPtr)(aSrcNativeVariant.ToInt64 () +
603 i * SizeOf (typeof(Variant))));
609 public static int GetStartComSlot (Type t)
612 throw new PlatformNotSupportedException ();
614 throw new NotImplementedException ();
618 #if !FULL_AOT_RUNTIME
620 [Obsolete ("This method has been deprecated")]
621 public static Thread GetThreadFromFiberCookie (int cookie)
623 throw new NotImplementedException ();
626 public static object GetTypedObjectForIUnknown (IntPtr pUnk, Type t)
628 ComInteropProxy proxy = new ComInteropProxy (pUnk, t);
629 __ComObject co = (__ComObject)proxy.GetTransparentProxy ();
630 foreach (Type itf in t.GetInterfaces ()) {
631 if ((itf.Attributes & TypeAttributes.Import) == TypeAttributes.Import) {
632 if (co.GetInterface (itf) == IntPtr.Zero)
640 public static Type GetTypeForITypeInfo (IntPtr piTypeInfo)
642 throw new NotImplementedException ();
647 public static string GetTypeInfoName (UCOMITypeInfo pTI)
649 throw new NotImplementedException ();
654 public static Guid GetTypeLibGuid (UCOMITypeLib pTLB)
656 throw new NotImplementedException ();
660 public static Guid GetTypeLibGuid (ITypeLib typelib)
662 throw new NotImplementedException ();
666 public static Guid GetTypeLibGuidForAssembly (Assembly asm)
668 throw new NotImplementedException ();
673 public static int GetTypeLibLcid (UCOMITypeLib pTLB)
675 throw new NotImplementedException ();
679 public static int GetTypeLibLcid (ITypeLib typelib)
681 throw new NotImplementedException ();
686 public static string GetTypeLibName (UCOMITypeLib pTLB)
688 throw new NotImplementedException ();
692 public static string GetTypeLibName (ITypeLib typelib)
694 throw new NotImplementedException ();
698 public static void GetTypeLibVersionForAssembly (Assembly inputAssembly, out int majorVersion, out int minorVersion)
700 throw new NotImplementedException ();
704 [Obsolete ("This method has been deprecated")]
705 public static IntPtr GetUnmanagedThunkForManagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
707 throw new NotImplementedException ();
711 public static bool IsTypeVisibleFromCom (Type t)
713 throw new NotImplementedException ();
717 public static int NumParamBytes (MethodInfo m)
719 throw new NotImplementedException ();
721 #endif // !FULL_AOT_RUNTIME
723 public static Type GetTypeFromCLSID (Guid clsid)
725 throw new PlatformNotSupportedException ();
728 public static string GetTypeInfoName (ITypeInfo typeInfo)
730 throw new PlatformNotSupportedException ();
733 public static object GetUniqueObjectForIUnknown (IntPtr unknown)
735 throw new PlatformNotSupportedException ();
739 [MethodImplAttribute (MethodImplOptions.InternalCall)]
740 public extern static bool IsComObject (object o);
742 public static bool IsComObject (object o)
748 [MethodImplAttribute(MethodImplOptions.InternalCall)]
749 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
750 public static extern int GetLastWin32Error();
752 [MethodImplAttribute(MethodImplOptions.InternalCall)]
753 public extern static IntPtr OffsetOf (Type t, string fieldName);
755 public static IntPtr OffsetOf<T> (string fieldName) {
756 return OffsetOf (typeof (T), fieldName);
759 [MethodImplAttribute(MethodImplOptions.InternalCall)]
760 public extern static void Prelink (MethodInfo m);
762 [MethodImplAttribute(MethodImplOptions.InternalCall)]
763 public extern static void PrelinkAll (Type c);
765 [MethodImplAttribute(MethodImplOptions.InternalCall)]
766 public extern static string PtrToStringAnsi (IntPtr ptr);
768 [MethodImplAttribute(MethodImplOptions.InternalCall)]
769 public extern static string PtrToStringAnsi (IntPtr ptr, int len);
771 public static string PtrToStringUTF8 (IntPtr ptr)
773 return PtrToStringAnsi (ptr);
776 public static string PtrToStringUTF8 (IntPtr ptr, int byteLen)
778 return PtrToStringAnsi (ptr, byteLen);
781 public static string PtrToStringAuto (IntPtr ptr)
783 return SystemDefaultCharSize == 2
784 ? PtrToStringUni (ptr) : PtrToStringAnsi (ptr);
787 public static string PtrToStringAuto (IntPtr ptr, int len)
789 return SystemDefaultCharSize == 2
790 ? PtrToStringUni (ptr, len) : PtrToStringAnsi (ptr, len);
793 [MethodImplAttribute(MethodImplOptions.InternalCall)]
794 public extern static string PtrToStringUni (IntPtr ptr);
796 [MethodImplAttribute(MethodImplOptions.InternalCall)]
797 public extern static string PtrToStringUni (IntPtr ptr, int len);
799 [MethodImplAttribute(MethodImplOptions.InternalCall)]
800 public extern static string PtrToStringBSTR (IntPtr ptr);
802 [MethodImplAttribute(MethodImplOptions.InternalCall)]
804 public extern static void PtrToStructure (IntPtr ptr, object structure);
806 [MethodImplAttribute(MethodImplOptions.InternalCall)]
808 public extern static object PtrToStructure (IntPtr ptr, Type structureType);
810 public static void PtrToStructure<T> (IntPtr ptr, T structure) {
811 PtrToStructure (ptr, (object)structure);
814 public static T PtrToStructure<T> (IntPtr ptr) {
815 return (T) PtrToStructure (ptr, typeof (T));
819 [MethodImplAttribute (MethodImplOptions.InternalCall)]
820 private extern static int QueryInterfaceInternal (IntPtr pUnk, ref Guid iid, out IntPtr ppv);
823 public static int QueryInterface (IntPtr pUnk, ref Guid iid, out IntPtr ppv)
826 if (pUnk == IntPtr.Zero)
827 throw new ArgumentException ("Value cannot be null.", "pUnk");
828 return QueryInterfaceInternal (pUnk, ref iid, out ppv);
830 throw new NotImplementedException ();
834 public static byte ReadByte (IntPtr ptr)
841 public static byte ReadByte (IntPtr ptr, int ofs) {
843 return *((byte*)ptr + ofs);
848 [SuppressUnmanagedCodeSecurity]
849 public static byte ReadByte ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
851 throw new NotImplementedException ();
854 public unsafe static short ReadInt16 (IntPtr ptr)
856 byte *addr = (byte *) ptr;
858 // The mono JIT can't inline this due to the hight number of calls
859 // return ReadInt16 (ptr, 0);
861 if (((uint)addr & 1) == 0)
862 return *(short*)addr;
865 Buffer.Memcpy ((byte*)&s, (byte*)ptr, 2);
869 public unsafe static short ReadInt16 (IntPtr ptr, int ofs)
871 byte *addr = ((byte *) ptr) + ofs;
873 if (((uint) addr & 1) == 0)
874 return *(short*)addr;
877 Buffer.Memcpy ((byte*)&s, addr, 2);
882 [SuppressUnmanagedCodeSecurity]
883 public static short ReadInt16 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
885 throw new NotImplementedException ();
888 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
889 public unsafe static int ReadInt32 (IntPtr ptr)
891 byte *addr = (byte *) ptr;
893 if (((uint)addr & 3) == 0)
897 Buffer.Memcpy ((byte*)&s, addr, 4);
901 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
902 public unsafe static int ReadInt32 (IntPtr ptr, int ofs)
904 byte *addr = ((byte *) ptr) + ofs;
906 if ((((int) addr) & 3) == 0)
910 Buffer.Memcpy ((byte*)&s, addr, 4);
915 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
917 [SuppressUnmanagedCodeSecurity]
918 public static int ReadInt32 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
920 throw new NotImplementedException ();
923 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
924 public unsafe static long ReadInt64 (IntPtr ptr)
926 byte *addr = (byte *) ptr;
928 // The real alignment might be 4 on some platforms, but this is just an optimization,
929 // so it doesn't matter.
930 if (((uint) addr & 7) == 0)
934 Buffer.Memcpy ((byte*)&s, addr, 8);
938 public unsafe static long ReadInt64 (IntPtr ptr, int ofs)
940 byte *addr = ((byte *) ptr) + ofs;
942 if (((uint) addr & 7) == 0)
946 Buffer.Memcpy ((byte*)&s, addr, 8);
950 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
952 [SuppressUnmanagedCodeSecurity]
953 public static long ReadInt64 ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
955 throw new NotImplementedException ();
958 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
959 public static IntPtr ReadIntPtr (IntPtr ptr)
961 if (IntPtr.Size == 4)
962 return (IntPtr)ReadInt32 (ptr);
964 return (IntPtr)ReadInt64 (ptr);
967 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
968 public static IntPtr ReadIntPtr (IntPtr ptr, int ofs)
970 if (IntPtr.Size == 4)
971 return (IntPtr)ReadInt32 (ptr, ofs);
973 return (IntPtr)ReadInt64 (ptr, ofs);
976 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
978 public static IntPtr ReadIntPtr ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
980 throw new NotImplementedException ();
983 [MethodImplAttribute (MethodImplOptions.InternalCall)]
984 public extern static IntPtr ReAllocCoTaskMem (IntPtr pv, int cb);
986 [MethodImplAttribute(MethodImplOptions.InternalCall)]
987 public extern static IntPtr ReAllocHGlobal (IntPtr pv, IntPtr cb);
990 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
991 [MethodImplAttribute (MethodImplOptions.InternalCall)]
992 private extern static int ReleaseInternal (IntPtr pUnk);
995 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
996 public static int Release (IntPtr pUnk)
999 if (pUnk == IntPtr.Zero)
1000 throw new ArgumentException ("Value cannot be null.", "pUnk");
1002 return ReleaseInternal (pUnk);
1004 throw new NotImplementedException ();
1008 #if !FULL_AOT_RUNTIME
1009 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1010 private extern static int ReleaseComObjectInternal (object co);
1013 public static int ReleaseComObject (object o)
1015 #if FULL_AOT_RUNTIME
1016 throw new PlatformNotSupportedException ();
1019 throw new ArgumentException ("Value cannot be null.", "o");
1020 if (!IsComObject (o))
1021 throw new ArgumentException ("Value must be a Com object.", "o");
1022 return ReleaseComObjectInternal (o);
1026 #if !FULL_AOT_RUNTIME
1029 public static void ReleaseThreadCache()
1031 throw new NotImplementedException ();
1034 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
1035 public static bool SetComObjectData (object obj, object key, object data)
1037 throw new NotSupportedException ("MSDN states user code should never need to call this method.");
1042 public static int SizeOf (object structure)
1044 return SizeOf (structure.GetType ());
1047 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1048 public extern static int SizeOf (Type t);
1050 public static int SizeOf<T> () {
1051 return SizeOf (typeof (T));
1054 public static int SizeOf<T> (T structure) {
1055 return SizeOf (structure.GetType ());
1058 internal static uint SizeOfType (Type type)
1060 return (uint) SizeOf (type);
1063 internal static uint AlignedSizeOf<T> () where T : struct
1065 uint size = SizeOfType (typeof (T));
1066 if (size == 1 || size == 2)
1068 if (IntPtr.Size == 8 && size == 4)
1070 return (size + 3) & (~((uint)3));
1073 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1074 public extern static IntPtr StringToBSTR (string s);
1076 public static IntPtr StringToCoTaskMemAnsi (string s)
1078 return StringToAllocatedMemoryUTF8 (s);
1081 public static IntPtr StringToCoTaskMemAuto (string s)
1083 return SystemDefaultCharSize == 2
1084 ? StringToCoTaskMemUni (s) : StringToCoTaskMemAnsi (s);
1087 public static IntPtr StringToCoTaskMemUni (string s)
1089 int length = s.Length + 1;
1090 IntPtr ctm = AllocCoTaskMem (length * 2);
1092 char[] asChars = new char[length];
1093 s.CopyTo (0, asChars, 0, s.Length);
1094 asChars[s.Length] = '\0';
1096 copy_to_unmanaged (asChars, 0, ctm, length);
1100 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1101 public extern static IntPtr StringToHGlobalAnsi (string s);
1103 unsafe public static IntPtr StringToAllocatedMemoryUTF8(String s)
1105 const int MAX_UTF8_CHAR_SIZE = 3;
1109 int nb = (s.Length + 1) * MAX_UTF8_CHAR_SIZE;
1111 // Overflow checking
1113 throw new ArgumentOutOfRangeException("s");
1115 IntPtr pMem = AllocCoTaskMemSize(new UIntPtr((uint)nb +1));
1117 if (pMem == IntPtr.Zero)
1118 throw new OutOfMemoryException();
1120 byte* pbMem = (byte*)pMem;
1121 int nbWritten = s.GetBytesFromEncoding(pbMem, nb, Encoding.UTF8);
1122 pbMem[nbWritten] = 0;
1126 public static IntPtr StringToHGlobalAuto (string s)
1128 return SystemDefaultCharSize == 2
1129 ? StringToHGlobalUni (s) : StringToHGlobalAnsi (s);
1132 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1133 public extern static IntPtr StringToHGlobalUni (string s);
1135 public static IntPtr SecureStringToBSTR (SecureString s)
1138 throw new ArgumentNullException ("s");
1140 byte[] buffer = s.GetBuffer ();
1143 // SecureString doesn't take endian-ness into account.
1144 // Therefore swap bytes here before we send it to c-side if little-endian.
1145 if (BitConverter.IsLittleEndian) {
1146 for (int i = 0; i < buffer.Length; i += 2) {
1148 buffer[i] = buffer[i + 1];
1152 return BufferToBSTR (buffer, len);
1155 public static IntPtr SecureStringToCoTaskMemAnsi (SecureString s)
1158 throw new ArgumentNullException ("s");
1160 IntPtr ctm = AllocCoTaskMem (len + 1);
1161 byte [] copy = new byte [len+1];
1164 byte [] buffer = s.GetBuffer ();
1166 for (; i < len; i++, j += 2){
1167 copy [i] = buffer [j+1];
1172 copy_to_unmanaged (copy, 0, ctm, len+1);
1174 // Ensure that we clear the buffer.
1175 for (int i = len; i > 0; ){
1183 public static IntPtr SecureStringToCoTaskMemUnicode (SecureString s)
1186 throw new ArgumentNullException ("s");
1188 IntPtr ctm = AllocCoTaskMem (len * 2 + 2);
1189 byte [] buffer = null;
1191 buffer = s.GetBuffer ();
1192 for (int i = 0; i < len; i++)
1193 WriteInt16 (ctm, i * 2, (short) ((buffer [(i*2)] << 8) | (buffer [i*2+1])));
1194 WriteInt16 (ctm, buffer.Length, 0);
1197 for (int i = buffer.Length; i > 0; ){
1205 public static IntPtr SecureStringToGlobalAllocAnsi (SecureString s)
1208 throw new ArgumentNullException ("s");
1209 return SecureStringToCoTaskMemAnsi (s);
1212 public static IntPtr SecureStringToGlobalAllocUnicode (SecureString s)
1215 throw new ArgumentNullException ("s");
1216 return SecureStringToCoTaskMemUnicode (s);
1219 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
1221 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1222 public extern static void StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld);
1224 public static void StructureToPtr<T> (T structure, IntPtr ptr, bool fDeleteOld) {
1225 StructureToPtr ((object)structure, ptr, fDeleteOld);
1228 public static void ThrowExceptionForHR (int errorCode) {
1229 Exception ex = GetExceptionForHR (errorCode);
1234 public static void ThrowExceptionForHR (int errorCode, IntPtr errorInfo) {
1235 Exception ex = GetExceptionForHR (errorCode, errorInfo);
1241 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1242 public extern static IntPtr BufferToBSTR (Array ptr, int slen);
1244 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1245 public extern static IntPtr UnsafeAddrOfPinnedArrayElement (Array arr, int index);
1247 public static IntPtr UnsafeAddrOfPinnedArrayElement<T> (T[] arr, int index) {
1248 return UnsafeAddrOfPinnedArrayElement ((Array)arr, index);
1251 public static void WriteByte (IntPtr ptr, byte val)
1258 public static void WriteByte (IntPtr ptr, int ofs, byte val) {
1260 *(byte*)(IntPtr.Add (ptr, ofs)) = val;
1265 [SuppressUnmanagedCodeSecurity]
1266 public static void WriteByte ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, byte val)
1268 throw new NotImplementedException ();
1271 public static unsafe void WriteInt16 (IntPtr ptr, short val)
1273 byte *addr = (byte *) ptr;
1275 if (((uint)addr & 1) == 0)
1276 *(short*)addr = val;
1278 Buffer.Memcpy (addr, (byte*)&val, 2);
1281 public static unsafe void WriteInt16 (IntPtr ptr, int ofs, short val)
1283 byte *addr = ((byte *) ptr) + ofs;
1285 if (((uint)addr & 1) == 0)
1286 *(short*)addr = val;
1288 Buffer.Memcpy (addr, (byte*)&val, 2);
1293 [SuppressUnmanagedCodeSecurity]
1294 public static void WriteInt16 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, short val)
1296 throw new NotImplementedException ();
1299 public static void WriteInt16 (IntPtr ptr, char val)
1301 WriteInt16 (ptr, 0, (short)val);
1304 public static void WriteInt16 (IntPtr ptr, int ofs, char val)
1306 WriteInt16 (ptr, ofs, (short)val);
1310 public static void WriteInt16([In, Out] object ptr, int ofs, char val)
1312 throw new NotImplementedException ();
1315 public static unsafe void WriteInt32 (IntPtr ptr, int val)
1317 byte *addr = (byte *) ptr;
1319 if (((uint)addr & 3) == 0)
1322 Buffer.Memcpy (addr, (byte*)&val, 4);
1326 public unsafe static void WriteInt32 (IntPtr ptr, int ofs, int val)
1328 byte *addr = ((byte *) ptr) + ofs;
1330 if (((uint)addr & 3) == 0)
1333 Buffer.Memcpy (addr, (byte*)&val, 4);
1338 [SuppressUnmanagedCodeSecurity]
1339 public static void WriteInt32([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, int val)
1341 throw new NotImplementedException ();
1344 public static unsafe void WriteInt64 (IntPtr ptr, long val)
1346 byte *addr = (byte *) ptr;
1348 // The real alignment might be 4 on some platforms, but this is just an optimization,
1349 // so it doesn't matter.
1350 if (((uint)addr & 7) == 0)
1353 Buffer.Memcpy (addr, (byte*)&val, 8);
1356 public static unsafe void WriteInt64 (IntPtr ptr, int ofs, long val)
1358 byte *addr = ((byte *) ptr) + ofs;
1360 // The real alignment might be 4 on some platforms, but this is just an optimization,
1361 // so it doesn't matter.
1362 if (((uint)addr & 7) == 0)
1365 Buffer.Memcpy (addr, (byte*)&val, 8);
1369 [SuppressUnmanagedCodeSecurity]
1370 public static void WriteInt64 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, long val)
1372 throw new NotImplementedException ();
1375 public static void WriteIntPtr (IntPtr ptr, IntPtr val)
1377 if (IntPtr.Size == 4)
1378 WriteInt32 (ptr, (int)val);
1380 WriteInt64 (ptr, (long)val);
1383 public static void WriteIntPtr (IntPtr ptr, int ofs, IntPtr val)
1385 if (IntPtr.Size == 4)
1386 WriteInt32 (ptr, ofs, (int)val);
1388 WriteInt64 (ptr, ofs, (long)val);
1392 public static void WriteIntPtr([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, IntPtr val)
1394 throw new NotImplementedException ();
1397 private static Exception ConvertHrToException (int errorCode)
1399 const int MSEE_E_APPDOMAINUNLOADED = unchecked ((int)0x80131014L);
1400 const int COR_E_APPLICATION = unchecked ((int)0x80131600L);
1401 const int E_INVALIDARG = unchecked ((int)0x80070057);
1402 const int COR_E_ARGUMENTOUTOFRANGE = unchecked ((int)0x80131502L);
1403 const int COR_E_ARITHMETIC = unchecked ((int)0x80070216);
1404 const int COR_E_ARRAYTYPEMISMATCH = unchecked ((int)0x80131503L);
1405 const int COR_E_BADIMAGEFORMAT = unchecked ((int)0x8007000BL);
1406 const int ERROR_BAD_FORMAT = unchecked ((int)0x0B);
1407 //const int COR_E_COMEMULATE_ERROR = unchecked ((int)?);
1408 const int COR_E_CONTEXTMARSHAL = unchecked ((int)0x80131504L);
1409 //const int COR_E_CORE = unchecked ((int)?);
1410 const int NTE_FAIL = unchecked ((int)0x80090020L);
1411 const int COR_E_DIRECTORYNOTFOUND = unchecked ((int)0x80070003L);
1412 const int ERROR_PATH_NOT_FOUND = unchecked ((int)0x03);
1413 const int COR_E_DIVIDEBYZERO = unchecked ((int)0x80020012L);
1414 const int COR_E_DUPLICATEWAITOBJECT = unchecked ((int)0x80131529L);
1415 const int COR_E_ENDOFSTREAM = unchecked ((int)0x80070026L);
1416 const int COR_E_TYPELOAD = unchecked ((int)0x80131522L);
1417 const int COR_E_EXCEPTION = unchecked ((int)0x80131500L);
1418 const int COR_E_EXECUTIONENGINE = unchecked ((int)0x80131506L);
1419 const int COR_E_FIELDACCESS = unchecked ((int)0x80131507L);
1420 const int COR_E_FILENOTFOUND = unchecked ((int)0x80070002L);
1421 const int ERROR_FILE_NOT_FOUND = unchecked ((int)0x02);
1422 const int COR_E_FORMAT = unchecked ((int)0x80131537L);
1423 const int COR_E_INDEXOUTOFRANGE = unchecked ((int)0x80131508L);
1424 const int COR_E_INVALIDCAST = unchecked ((int)0x80004002L);
1425 const int COR_E_INVALIDCOMOBJECT = unchecked ((int)0x80131527L);
1426 const int COR_E_INVALIDFILTERCRITERIA = unchecked ((int)0x80131601L);
1427 const int COR_E_INVALIDOLEVARIANTTYPE = unchecked ((int)0x80131531L);
1428 const int COR_E_INVALIDOPERATION = unchecked ((int)0x80131509L);
1429 const int COR_E_IO = unchecked ((int)0x80131620L);
1430 const int COR_E_MEMBERACCESS = unchecked ((int)0x8013151AL);
1431 const int COR_E_METHODACCESS = unchecked ((int)0x80131510L);
1432 const int COR_E_MISSINGFIELD = unchecked ((int)0x80131511L);
1433 const int COR_E_MISSINGMANIFESTRESOURCE = unchecked ((int)0x80131532L);
1434 const int COR_E_MISSINGMEMBER = unchecked ((int)0x80131512L);
1435 const int COR_E_MISSINGMETHOD = unchecked ((int)0x80131513L);
1436 const int COR_E_MULTICASTNOTSUPPORTED = unchecked ((int)0x80131514L);
1437 const int COR_E_NOTFINITENUMBER = unchecked ((int)0x80131528L);
1438 const int E_NOTIMPL = unchecked ((int)0x80004001L);
1439 const int COR_E_NOTSUPPORTED = unchecked ((int)0x80131515L);
1440 const int COR_E_NULLREFERENCE = unchecked ((int)0x80004003L);
1441 const int E_OUTOFMEMORY = unchecked ((int)0x8007000EL);
1442 const int COR_E_OVERFLOW = unchecked ((int)0x80131516L);
1443 const int COR_E_PATHTOOLONG = unchecked ((int)0x800700CEL);
1444 const int ERROR_FILENAME_EXCED_RANGE = unchecked ((int)0xCE);
1445 const int COR_E_RANK = unchecked ((int)0x80131517L);
1446 const int COR_E_REFLECTIONTYPELOAD = unchecked ((int)0x80131602L);
1447 const int COR_E_REMOTING = unchecked ((int)0x8013150BL);
1448 const int COR_E_SAFEARRAYTYPEMISMATCH = unchecked ((int)0x80131533L);
1449 const int COR_E_SECURITY = unchecked ((int)0x8013150AL);
1450 const int COR_E_SERIALIZATION = unchecked ((int)0x8013150CL);
1451 const int COR_E_STACKOVERFLOW = unchecked ((int)0x800703E9L);
1452 const int ERROR_STACK_OVERFLOW = unchecked ((int)0x03E9);
1453 const int COR_E_SYNCHRONIZATIONLOCK = unchecked ((int)0x80131518L);
1454 const int COR_E_SYSTEM = unchecked ((int)0x80131501L);
1455 const int COR_E_TARGET = unchecked ((int)0x80131603L);
1456 const int COR_E_TARGETINVOCATION = unchecked ((int)0x80131604L);
1457 const int COR_E_TARGETPARAMCOUNT = unchecked ((int)0x8002000EL);
1458 //const int COR_E_THREADABORTED = unchecked ((int)0x80131530L);
1459 const int COR_E_THREADINTERRUPTED = unchecked ((int)0x80131519L);
1460 const int COR_E_THREADSTATE = unchecked ((int)0x80131520L);
1461 //const int COR_E_THREADSTOP = unchecked ((int)0x80131521L);
1462 const int COR_E_TYPEINITIALIZATION = unchecked ((int)0x80131534L);
1463 const int COR_E_VERIFICATION = unchecked ((int)0x8013150DL);
1464 //const int COR_E_WEAKREFERENCE = unchecked ((int)?);
1465 //const int COR_E_VTABLECALLSNOTSUPPORTED = unchecked ((int));
1467 switch (errorCode) {
1468 case MSEE_E_APPDOMAINUNLOADED:
1469 return new AppDomainUnloadedException ();
1470 case COR_E_APPLICATION:
1471 return new ApplicationException ();
1473 return new ArgumentException ();
1474 case COR_E_ARGUMENTOUTOFRANGE:
1475 return new ArgumentOutOfRangeException ();
1476 case COR_E_ARITHMETIC:
1477 return new ArithmeticException ();
1478 case COR_E_ARRAYTYPEMISMATCH:
1479 return new ArrayTypeMismatchException ();
1480 case COR_E_BADIMAGEFORMAT:
1481 case ERROR_BAD_FORMAT:
1482 return new BadImageFormatException ();
1483 // case COR_E_COMEMULATE_ERROR:
1484 // return new COMEmulateException ();
1485 case COR_E_CONTEXTMARSHAL:
1486 return new ContextMarshalException ();
1488 // return new CoreException ();
1490 return new System.Security.Cryptography.CryptographicException ();
1491 case COR_E_DIRECTORYNOTFOUND:
1492 case ERROR_PATH_NOT_FOUND:
1493 return new System.IO.DirectoryNotFoundException ();
1494 case COR_E_DIVIDEBYZERO:
1495 return new DivideByZeroException ();
1496 case COR_E_DUPLICATEWAITOBJECT:
1497 return new DuplicateWaitObjectException ();
1498 case COR_E_ENDOFSTREAM:
1499 return new System.IO.EndOfStreamException ();
1500 case COR_E_EXCEPTION:
1501 return new Exception ();
1502 case COR_E_EXECUTIONENGINE:
1503 return new ExecutionEngineException ();
1504 case COR_E_FIELDACCESS:
1505 return new FieldAccessException ();
1506 case COR_E_FILENOTFOUND:
1507 case ERROR_FILE_NOT_FOUND:
1508 return new System.IO.FileNotFoundException ();
1510 return new FormatException ();
1511 case COR_E_INDEXOUTOFRANGE:
1512 return new IndexOutOfRangeException ();
1513 case COR_E_INVALIDCAST:
1514 // E_NOINTERFACE has same value as COR_E_INVALIDCAST
1515 return new InvalidCastException ();
1516 case COR_E_INVALIDCOMOBJECT:
1517 return new InvalidComObjectException ();
1518 case COR_E_INVALIDFILTERCRITERIA:
1519 return new InvalidFilterCriteriaException ();
1520 case COR_E_INVALIDOLEVARIANTTYPE:
1521 return new InvalidOleVariantTypeException ();
1522 case COR_E_INVALIDOPERATION:
1523 return new InvalidOperationException ();
1525 return new System.IO.IOException ();
1526 case COR_E_MEMBERACCESS:
1527 return new MemberAccessException ();
1528 case COR_E_METHODACCESS:
1529 return new MethodAccessException ();
1530 case COR_E_MISSINGFIELD:
1531 return new MissingFieldException ();
1532 case COR_E_MISSINGMANIFESTRESOURCE:
1533 return new System.Resources.MissingManifestResourceException ();
1534 case COR_E_MISSINGMEMBER:
1535 return new MissingMemberException ();
1536 case COR_E_MISSINGMETHOD:
1537 return new MissingMethodException ();
1538 case COR_E_MULTICASTNOTSUPPORTED:
1539 return new MulticastNotSupportedException ();
1540 case COR_E_NOTFINITENUMBER:
1541 return new NotFiniteNumberException ();
1543 return new NotImplementedException ();
1544 case COR_E_NOTSUPPORTED:
1545 return new NotSupportedException ();
1546 case COR_E_NULLREFERENCE:
1547 // E_POINTER has the same value as COR_E_NULLREFERENCE
1548 return new NullReferenceException ();
1550 // COR_E_OUTOFMEMORY has the same value as E_OUTOFMEMORY
1551 return new OutOfMemoryException ();
1552 case COR_E_OVERFLOW:
1553 return new OverflowException ();
1554 case COR_E_PATHTOOLONG:
1555 case ERROR_FILENAME_EXCED_RANGE:
1556 return new System.IO.PathTooLongException ();
1558 return new RankException ();
1559 case COR_E_REFLECTIONTYPELOAD:
1560 return new System.Reflection.ReflectionTypeLoadException (new Type[] { }, new Exception[] { });
1561 case COR_E_REMOTING:
1562 return new System.Runtime.Remoting.RemotingException ();
1563 case COR_E_SAFEARRAYTYPEMISMATCH:
1564 return new SafeArrayTypeMismatchException ();
1565 case COR_E_SECURITY:
1566 return new SecurityException ();
1567 case COR_E_SERIALIZATION:
1568 return new System.Runtime.Serialization.SerializationException ();
1569 case COR_E_STACKOVERFLOW:
1570 case ERROR_STACK_OVERFLOW:
1571 return new StackOverflowException ();
1572 case COR_E_SYNCHRONIZATIONLOCK:
1573 return new SynchronizationLockException ();
1575 return new SystemException ();
1577 return new TargetException ();
1578 case COR_E_TARGETINVOCATION:
1579 return new System.Reflection.TargetInvocationException (null);
1580 case COR_E_TARGETPARAMCOUNT:
1581 return new TargetParameterCountException ();
1582 // case COR_E_THREADABORTED:
1583 // ThreadAbortException c'tor is inaccessible
1584 // return new System.Threading.ThreadAbortException ();
1585 case COR_E_THREADINTERRUPTED:
1586 return new ThreadInterruptedException ();
1587 case COR_E_THREADSTATE:
1588 return new ThreadStateException ();
1589 // case COR_E_THREADSTOP:
1590 // ThreadStopException does not exist
1591 // return new System.Threading.ThreadStopException ();
1592 case COR_E_TYPELOAD:
1593 return new TypeLoadException ();
1594 // MSDN lists COR_E_TYPELOAD twice with different exceptions.
1595 // return new EntryPointNotFoundException ();
1596 case COR_E_TYPEINITIALIZATION:
1597 return new TypeInitializationException("", null);
1598 case COR_E_VERIFICATION:
1599 return new VerificationException ();
1600 // case COR_E_WEAKREFERENCE:
1601 // return new WeakReferenceException ();
1602 // case COR_E_VTABLECALLSNOTSUPPORTED:
1603 // return new VTableCallsNotSupportedException ();
1606 return new COMException ("", errorCode);
1610 #if FEATURE_COMINTEROP
1611 [DllImport ("oleaut32.dll", CharSet=CharSet.Unicode, EntryPoint = "SetErrorInfo")]
1612 static extern int _SetErrorInfo (int dwReserved,
1613 [MarshalAs(UnmanagedType.Interface)] IErrorInfo pIErrorInfo);
1615 [DllImport ("oleaut32.dll", CharSet=CharSet.Unicode, EntryPoint = "GetErrorInfo")]
1616 static extern int _GetErrorInfo (int dwReserved,
1617 [MarshalAs(UnmanagedType.Interface)] out IErrorInfo ppIErrorInfo);
1619 static bool SetErrorInfoNotAvailable;
1620 static bool GetErrorInfoNotAvailable;
1622 internal static int SetErrorInfo (int dwReserved, IErrorInfo errorInfo)
1627 if (SetErrorInfoNotAvailable)
1631 retVal = _SetErrorInfo (dwReserved, errorInfo);
1634 // ignore any exception - probably there's no suitable SetErrorInfo
1635 // method available.
1636 SetErrorInfoNotAvailable = true;
1641 internal static int GetErrorInfo (int dwReserved, out IErrorInfo errorInfo)
1646 if (GetErrorInfoNotAvailable)
1650 retVal = _GetErrorInfo (dwReserved, out errorInfo);
1653 // ignore any exception - probably there's no suitable GetErrorInfo
1654 // method available.
1655 GetErrorInfoNotAvailable = true;
1660 public static Exception GetExceptionForHR (int errorCode)
1662 return GetExceptionForHR (errorCode, IntPtr.Zero);
1665 public static Exception GetExceptionForHR (int errorCode, IntPtr errorInfo)
1667 #if FEATURE_COMINTEROP
1668 IErrorInfo info = null;
1669 if (errorInfo != (IntPtr)(-1)) {
1670 if (errorInfo == IntPtr.Zero) {
1671 if (GetErrorInfo (0, out info) != 0) {
1675 info = Marshal.GetObjectForIUnknown (errorInfo) as IErrorInfo;
1679 if (info is ManagedErrorInfo && ((ManagedErrorInfo) info).Exception._HResult == errorCode) {
1680 return ((ManagedErrorInfo) info).Exception;
1683 Exception e = ConvertHrToException (errorCode);
1684 if (info != null && e != null) {
1686 info.GetHelpContext (out helpContext);
1688 info.GetSource (out str);
1690 info.GetDescription (out str);
1692 info.GetHelpFile (out str);
1694 if (helpContext == 0) {
1697 e.HelpLink = string.Format ("{0}#{1}", str, helpContext);
1702 return ConvertHrToException (errorCode);
1706 public static int FinalReleaseComObject (object o)
1708 while (ReleaseComObject (o) != 0);
1712 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1713 private static extern Delegate GetDelegateForFunctionPointerInternal (IntPtr ptr, Type t);
1715 public static Delegate GetDelegateForFunctionPointer (IntPtr ptr, Type t)
1718 throw new ArgumentNullException ("t");
1719 if (!t.IsSubclassOf (typeof (MulticastDelegate)) || (t == typeof (MulticastDelegate)))
1720 throw new ArgumentException ("Type is not a delegate", "t");
1721 if (t.IsGenericType)
1722 throw new ArgumentException ("The specified Type must not be a generic type definition.");
1723 if (ptr == IntPtr.Zero)
1724 throw new ArgumentNullException ("ptr");
1726 return GetDelegateForFunctionPointerInternal (ptr, t);
1729 public static TDelegate GetDelegateForFunctionPointer<TDelegate> (IntPtr ptr) {
1730 return (TDelegate) (object) GetDelegateForFunctionPointer (ptr, typeof (TDelegate));
1733 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1734 private static extern IntPtr GetFunctionPointerForDelegateInternal (Delegate d);
1736 public static IntPtr GetFunctionPointerForDelegate (Delegate d)
1739 throw new ArgumentNullException ("d");
1741 return GetFunctionPointerForDelegateInternal (d);
1744 public static IntPtr GetFunctionPointerForDelegate<TDelegate> (TDelegate d) {
1746 throw new ArgumentNullException ("d");
1748 return GetFunctionPointerForDelegateInternal ((Delegate)(object)d);
1751 internal static void SetLastWin32Error (int error)
1755 #if FEATURE_COMINTEROP || MONO_COM
1756 // Copied from referencesource/mscorlib/system/runtime/interopservices/marshal.cs
1757 //====================================================================
1758 // return the raw IUnknown* for a COM Object not related to current
1760 // Does not call AddRef
1761 //====================================================================
1762 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1763 internal static extern IntPtr /* IUnknown* */ GetRawIUnknownForComObjectNoAddRef(Object o);
1765 // Copied from referencesource/mscorlib/system/runtime/interopservices/marshal.cs
1766 //====================================================================
1767 // Converts the CLR exception to an HRESULT. This function also sets
1768 // up an IErrorInfo for the exception.
1769 // This function is only used in WinRT and converts ObjectDisposedException
1771 //====================================================================
1772 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1773 internal static extern int GetHRForException_WinRT(Exception e);
1775 // Copied from referencesource/mscorlib/system/runtime/interopservices/marshal.cs
1776 //========================================================================
1777 // Create activation factory and wraps it with a unique RCW
1778 //========================================================================
1779 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1780 internal static extern object GetNativeActivationFactory(Type type);
1782 internal static IntPtr /* IUnknown* */ GetRawIUnknownForComObjectNoAddRef(Object o) {
1783 throw new NotSupportedException();
1786 internal static int GetHRForException_WinRT(Exception e) {
1787 throw new NotSupportedException();
1790 internal static object GetNativeActivationFactory(Type type) {
1791 throw new NotSupportedException();