1 // System.Runtime.InteropServices.Marshal.cs
3 // Sean MacIsaac (macisaac@ximian.com)
4 // Paolo Molaro (lupus@ximian.com)
5 // Dietmar Maurer (dietmar@ximian.com)
6 // Jonathan Chambers (joncham@gmail.com)
8 // (C) 2001-2002 Ximian, Inc.
11 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 using System.Collections;
34 using System.Collections.Generic;
35 using System.Runtime.CompilerServices;
37 using System.Security;
38 using System.Reflection;
39 using System.Threading;
41 using System.Runtime.ConstrainedExecution;
43 using System.Runtime.InteropServices.ComTypes;
47 namespace System.Runtime.InteropServices
49 public static class Marshal
52 public static readonly int SystemMaxDBCSCharSize = 2; // don't know what this is
53 public static readonly int SystemDefaultCharSize = Environment.IsRunningOnWindows ? 2 : 1;
56 [MethodImplAttribute (MethodImplOptions.InternalCall)]
57 private extern static int AddRefInternal (IntPtr pUnk);
60 public static int AddRef (IntPtr pUnk)
63 if (pUnk == IntPtr.Zero)
64 throw new ArgumentException ("Value cannot be null.", "pUnk");
65 return AddRefInternal (pUnk);
67 throw new NotImplementedException ();
71 [MethodImplAttribute(MethodImplOptions.InternalCall)]
72 public extern static IntPtr AllocCoTaskMem (int cb);
74 [MethodImplAttribute(MethodImplOptions.InternalCall)]
75 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
76 public extern static IntPtr AllocHGlobal (IntPtr cb);
78 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
79 public static IntPtr AllocHGlobal (int cb)
81 return AllocHGlobal ((IntPtr)cb);
85 public static object BindToMoniker (string monikerName)
87 throw new NotImplementedException ();
91 public static void ChangeWrapperHandleStrength (object otp, bool fIsWeak)
93 throw new NotImplementedException ();
96 [MethodImplAttribute(MethodImplOptions.InternalCall)]
97 internal extern static void copy_to_unmanaged (Array source, int startIndex,
98 IntPtr destination, int length);
100 [MethodImplAttribute(MethodImplOptions.InternalCall)]
101 internal extern static void copy_from_unmanaged (IntPtr source, int startIndex,
102 Array destination, int length);
104 public static void Copy (byte[] source, int startIndex, IntPtr destination, int length)
106 copy_to_unmanaged (source, startIndex, destination, length);
109 public static void Copy (char[] source, int startIndex, IntPtr destination, int length)
111 copy_to_unmanaged (source, startIndex, destination, length);
114 public static void Copy (short[] source, int startIndex, IntPtr destination, int length)
116 copy_to_unmanaged (source, startIndex, destination, length);
119 public static void Copy (int[] source, int startIndex, IntPtr destination, int length)
121 copy_to_unmanaged (source, startIndex, destination, length);
124 public static void Copy (long[] source, int startIndex, IntPtr destination, int length)
126 copy_to_unmanaged (source, startIndex, destination, length);
129 public static void Copy (float[] source, int startIndex, IntPtr destination, int length)
131 copy_to_unmanaged (source, startIndex, destination, length);
134 public static void Copy (double[] source, int startIndex, IntPtr destination, int length)
136 copy_to_unmanaged (source, startIndex, destination, length);
139 public static void Copy (IntPtr[] source, int startIndex, IntPtr destination, int length)
141 copy_to_unmanaged (source, startIndex, destination, length);
144 public static void Copy (IntPtr source, byte[] destination, int startIndex, int length)
146 copy_from_unmanaged (source, startIndex, destination, length);
149 public static void Copy (IntPtr source, char[] destination, int startIndex, int length)
151 copy_from_unmanaged (source, startIndex, destination, length);
154 public static void Copy (IntPtr source, short[] destination, int startIndex, int length)
156 copy_from_unmanaged (source, startIndex, destination, length);
159 public static void Copy (IntPtr source, int[] destination, int startIndex, int length)
161 copy_from_unmanaged (source, startIndex, destination, length);
164 public static void Copy (IntPtr source, long[] destination, int startIndex, int length)
166 copy_from_unmanaged (source, startIndex, destination, length);
169 public static void Copy (IntPtr source, float[] destination, int startIndex, int length)
171 copy_from_unmanaged (source, startIndex, destination, length);
174 public static void Copy (IntPtr source, double[] destination, int startIndex, int length)
176 copy_from_unmanaged (source, startIndex, destination, length);
179 public static void Copy (IntPtr source, IntPtr[] destination, int startIndex, int length)
181 copy_from_unmanaged (source, startIndex, destination, length);
184 public static IntPtr CreateAggregatedObject (IntPtr pOuter,
187 throw new NotImplementedException ();
191 public static IntPtr CreateAggregatedObject<T> (IntPtr pOuter, T o) {
192 return CreateAggregatedObject (pOuter, (object)o);
196 #if !FULL_AOT_RUNTIME
197 public static object CreateWrapperOfType (object o, Type t)
199 __ComObject co = o as __ComObject;
201 throw new ArgumentException ("o must derive from __ComObject", "o");
203 throw new ArgumentNullException ("t");
205 Type[] itfs = o.GetType ().GetInterfaces ();
206 foreach (Type itf in itfs) {
207 if (itf.IsImport && co.GetInterface (itf) == IntPtr.Zero)
208 throw new InvalidCastException ();
211 return ComInteropProxy.GetProxy (co.IUnknown, t).GetTransparentProxy ();
215 public static TWrapper CreateWrapperOfType<T, TWrapper> (T o) {
216 return (TWrapper)CreateWrapperOfType ((object)o, typeof (TWrapper));
221 [MethodImplAttribute(MethodImplOptions.InternalCall)]
223 public extern static void DestroyStructure (IntPtr ptr, Type structuretype);
226 public static void DestroyStructure<T> (IntPtr ptr) {
227 DestroyStructure (ptr, typeof (T));
231 [MethodImplAttribute(MethodImplOptions.InternalCall)]
232 public extern static void FreeBSTR (IntPtr ptr);
234 [MethodImplAttribute(MethodImplOptions.InternalCall)]
235 public extern static void FreeCoTaskMem (IntPtr ptr);
237 [MethodImplAttribute(MethodImplOptions.InternalCall)]
238 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
239 public extern static void FreeHGlobal (IntPtr hglobal);
241 static void ClearBSTR (IntPtr ptr)
243 int len = ReadInt32 (ptr, -4);
245 for (int i = 0; i < len; i++)
246 WriteByte (ptr, i, 0);
249 public static void ZeroFreeBSTR (IntPtr s)
255 static void ClearAnsi (IntPtr ptr)
257 for (int i = 0; ReadByte (ptr, i) != 0; i++)
258 WriteByte (ptr, i, 0);
261 static void ClearUnicode (IntPtr ptr)
263 for (int i = 0; ReadInt16 (ptr, i) != 0; i += 2)
264 WriteInt16 (ptr, i, 0);
267 public static void ZeroFreeCoTaskMemAnsi (IntPtr s)
273 public static void ZeroFreeCoTaskMemUnicode (IntPtr s)
279 public static void ZeroFreeGlobalAllocAnsi (IntPtr s)
285 public static void ZeroFreeGlobalAllocUnicode (IntPtr s)
291 #if !FULL_AOT_RUNTIME
292 public static Guid GenerateGuidForType (Type type)
297 public static string GenerateProgIdForType (Type type)
299 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (type);
301 foreach (var a in attrs)
303 var dt = a.Constructor.DeclaringType;
304 string name = dt.Name;
305 if (name == "ProgIdAttribute")
307 var args = a.ConstructorArguments;
308 string text = a.ConstructorArguments[0].Value as string;
317 return type.FullName;
321 public static object GetActiveObject (string progID)
323 throw new NotImplementedException ();
327 [MethodImplAttribute (MethodImplOptions.InternalCall)]
328 private extern static IntPtr GetCCW (object o, Type T);
330 private static IntPtr GetComInterfaceForObjectInternal (object o, Type T)
333 return ((__ComObject)o).GetInterface (T);
335 return GetCCW (o, T);
339 public static IntPtr GetComInterfaceForObject (object o, Type T)
342 IntPtr pItf = GetComInterfaceForObjectInternal (o, T);
346 throw new NotImplementedException ();
351 public static IntPtr GetComInterfaceForObject<T, TInterface> (T o) {
352 return GetComInterfaceForObject ((object)o, typeof (T));
357 public static IntPtr GetComInterfaceForObjectInContext (object o, Type t)
359 throw new NotImplementedException ();
362 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
363 public static object GetComObjectData (object obj, object key)
365 throw new NotSupportedException ("MSDN states user code should never need to call this method.");
369 [MethodImplAttribute(MethodImplOptions.InternalCall)]
370 private extern static int GetComSlotForMethodInfoInternal (MemberInfo m);
373 public static int GetComSlotForMethodInfo (MemberInfo m)
377 throw new ArgumentNullException ("m");
378 if (!(m is MethodInfo))
379 throw new ArgumentException ("The MemberInfo must be an interface method.", "m");
380 if (!m.DeclaringType.IsInterface)
381 throw new ArgumentException ("The MemberInfo must be an interface method.", "m");
382 return GetComSlotForMethodInfoInternal (m);
384 throw new NotImplementedException ();
389 public static int GetEndComSlot (Type t)
391 throw new NotImplementedException ();
395 public static int GetExceptionCode()
397 throw new NotImplementedException ();
402 public static IntPtr GetExceptionPointers()
404 throw new NotImplementedException ();
407 public static IntPtr GetHINSTANCE (Module m)
410 throw new ArgumentNullException ("m");
412 return m.GetHINSTANCE ();
414 #endif // !FULL_AOT_RUNTIME
416 #if !FULL_AOT_RUNTIME
417 [MonoTODO ("SetErrorInfo")]
418 public static int GetHRForException (Exception e)
424 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
425 public static int GetHRForLastWin32Error()
427 throw new NotImplementedException ();
430 [MethodImplAttribute (MethodImplOptions.InternalCall)]
431 private extern static IntPtr GetIDispatchForObjectInternal (object o);
433 public static IntPtr GetIDispatchForObject (object o)
435 IntPtr pUnk = GetIDispatchForObjectInternal (o);
436 // Internal method does not AddRef
442 public static IntPtr GetIDispatchForObjectInContext (object o)
444 throw new NotImplementedException ();
448 public static IntPtr GetITypeInfoForType (Type t)
450 throw new NotImplementedException ();
453 [MethodImplAttribute (MethodImplOptions.InternalCall)]
454 private extern static IntPtr GetIUnknownForObjectInternal (object o);
456 public static IntPtr GetIUnknownForObject (object o)
458 IntPtr pUnk = GetIUnknownForObjectInternal (o);
459 // Internal method does not AddRef
465 public static IntPtr GetIUnknownForObjectInContext (object o)
467 throw new NotImplementedException ();
471 [Obsolete ("This method has been deprecated")]
472 public static IntPtr GetManagedThunkForUnmanagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
474 throw new NotImplementedException ();
478 public static MemberInfo GetMethodInfoForComSlot (Type t, int slot, ref ComMemberType memberType)
480 throw new NotImplementedException ();
483 public static void GetNativeVariantForObject (object obj, IntPtr pDstNativeVariant)
485 Variant vt = new Variant();
487 Marshal.StructureToPtr(vt, pDstNativeVariant, false);
491 public static void GetNativeVariantForObject<T> (T obj, IntPtr pDstNativeVariant) {
492 GetNativeVariantForObject ((object)obj, pDstNativeVariant);
497 [MethodImplAttribute (MethodImplOptions.InternalCall)]
498 private static extern object GetObjectForCCW (IntPtr pUnk);
501 public static object GetObjectForIUnknown (IntPtr pUnk)
504 object obj = GetObjectForCCW (pUnk);
507 ComInteropProxy proxy = ComInteropProxy.GetProxy (pUnk, typeof (__ComObject));
508 obj = proxy.GetTransparentProxy ();
512 throw new NotImplementedException ();
516 public static object GetObjectForNativeVariant (IntPtr pSrcNativeVariant)
518 Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
519 return vt.GetValue();
523 public static T GetObjectForNativeVariant<T> (IntPtr pSrcNativeVariant) {
524 Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
525 return (T)vt.GetValue();
529 public static object[] GetObjectsForNativeVariants (IntPtr aSrcNativeVariant, int cVars)
532 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
533 object[] objects = new object[cVars];
534 for (int i = 0; i < cVars; i++)
535 objects[i] = GetObjectForNativeVariant ((IntPtr)(aSrcNativeVariant.ToInt64 () +
536 i * SizeOf (typeof(Variant))));
541 public static T[] GetObjectsForNativeVariants<T> (IntPtr aSrcNativeVariant, int cVars) {
543 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
544 T[] objects = new T[cVars];
545 for (int i = 0; i < cVars; i++)
546 objects[i] = GetObjectForNativeVariant<T> ((IntPtr)(aSrcNativeVariant.ToInt64 () +
547 i * SizeOf (typeof(Variant))));
553 public static int GetStartComSlot (Type t)
555 throw new NotImplementedException ();
559 [Obsolete ("This method has been deprecated")]
560 public static Thread GetThreadFromFiberCookie (int cookie)
562 throw new NotImplementedException ();
565 public static object GetTypedObjectForIUnknown (IntPtr pUnk, Type t)
567 ComInteropProxy proxy = new ComInteropProxy (pUnk, t);
568 __ComObject co = (__ComObject)proxy.GetTransparentProxy ();
569 foreach (Type itf in t.GetInterfaces ()) {
570 if ((itf.Attributes & TypeAttributes.Import) == TypeAttributes.Import) {
571 if (co.GetInterface (itf) == IntPtr.Zero)
579 public static Type GetTypeForITypeInfo (IntPtr piTypeInfo)
581 throw new NotImplementedException ();
585 public static Type GetTypeFromCLSID (Guid clsid)
587 throw new NotImplementedException ();
591 #if !FULL_AOT_RUNTIME
594 public static string GetTypeInfoName (UCOMITypeInfo pTI)
596 throw new NotImplementedException ();
599 public static string GetTypeInfoName (ITypeInfo typeInfo)
601 throw new NotImplementedException ();
606 public static Guid GetTypeLibGuid (UCOMITypeLib pTLB)
608 throw new NotImplementedException ();
612 public static Guid GetTypeLibGuid (ITypeLib typelib)
614 throw new NotImplementedException ();
618 public static Guid GetTypeLibGuidForAssembly (Assembly asm)
620 throw new NotImplementedException ();
625 public static int GetTypeLibLcid (UCOMITypeLib pTLB)
627 throw new NotImplementedException ();
631 public static int GetTypeLibLcid (ITypeLib typelib)
633 throw new NotImplementedException ();
638 public static string GetTypeLibName (UCOMITypeLib pTLB)
640 throw new NotImplementedException ();
644 public static string GetTypeLibName (ITypeLib typelib)
646 throw new NotImplementedException ();
650 public static void GetTypeLibVersionForAssembly (Assembly inputAssembly, out int majorVersion, out int minorVersion)
652 throw new NotImplementedException ();
655 public static object GetUniqueObjectForIUnknown (IntPtr unknown)
657 throw new NotImplementedException ();
662 [Obsolete ("This method has been deprecated")]
663 public static IntPtr GetUnmanagedThunkForManagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
665 throw new NotImplementedException ();
669 [MethodImplAttribute (MethodImplOptions.InternalCall)]
670 public extern static bool IsComObject (object o);
672 public static bool IsComObject (object o)
674 throw new NotImplementedException ();
679 public static bool IsTypeVisibleFromCom (Type t)
681 throw new NotImplementedException ();
685 public static int NumParamBytes (MethodInfo m)
687 throw new NotImplementedException ();
691 [MethodImplAttribute(MethodImplOptions.InternalCall)]
692 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
693 public static extern int GetLastWin32Error();
695 [MethodImplAttribute(MethodImplOptions.InternalCall)]
696 public extern static IntPtr OffsetOf (Type t, string fieldName);
699 public static IntPtr OffsetOf<T> (string fieldName) {
700 return OffsetOf (typeof (T), fieldName);
704 [MethodImplAttribute(MethodImplOptions.InternalCall)]
705 public extern static void Prelink (MethodInfo m);
707 [MethodImplAttribute(MethodImplOptions.InternalCall)]
708 public extern static void PrelinkAll (Type c);
710 [MethodImplAttribute(MethodImplOptions.InternalCall)]
711 public extern static string PtrToStringAnsi (IntPtr ptr);
713 [MethodImplAttribute(MethodImplOptions.InternalCall)]
714 public extern static string PtrToStringAnsi (IntPtr ptr, int len);
716 public static string PtrToStringAuto (IntPtr ptr)
718 return SystemDefaultCharSize == 2
719 ? PtrToStringUni (ptr) : PtrToStringAnsi (ptr);
722 public static string PtrToStringAuto (IntPtr ptr, int len)
724 return SystemDefaultCharSize == 2
725 ? PtrToStringUni (ptr, len) : PtrToStringAnsi (ptr, len);
728 [MethodImplAttribute(MethodImplOptions.InternalCall)]
729 public extern static string PtrToStringUni (IntPtr ptr);
731 [MethodImplAttribute(MethodImplOptions.InternalCall)]
732 public extern static string PtrToStringUni (IntPtr ptr, int len);
735 [MethodImplAttribute(MethodImplOptions.InternalCall)]
736 public extern static string PtrToStringBSTR (IntPtr ptr);
738 public static string PtrToStringBSTR (IntPtr ptr)
740 throw new NotImplementedException ();
744 [MethodImplAttribute(MethodImplOptions.InternalCall)]
746 public extern static void PtrToStructure (IntPtr ptr, object structure);
748 [MethodImplAttribute(MethodImplOptions.InternalCall)]
750 public extern static object PtrToStructure (IntPtr ptr, Type structureType);
753 public static void PtrToStructure<T> (IntPtr ptr, T structure) {
754 PtrToStructure (ptr, (object)structure);
757 public static T PtrToStructure<T> (IntPtr ptr) {
758 return (T) PtrToStructure (ptr, typeof (T));
763 [MethodImplAttribute (MethodImplOptions.InternalCall)]
764 private extern static int QueryInterfaceInternal (IntPtr pUnk, ref Guid iid, out IntPtr ppv);
767 public static int QueryInterface (IntPtr pUnk, ref Guid iid, out IntPtr ppv)
770 if (pUnk == IntPtr.Zero)
771 throw new ArgumentException ("Value cannot be null.", "pUnk");
772 return QueryInterfaceInternal (pUnk, ref iid, out ppv);
774 throw new NotImplementedException ();
778 public static byte ReadByte (IntPtr ptr)
785 public static byte ReadByte (IntPtr ptr, int ofs) {
787 return *((byte*)ptr + ofs);
792 [SuppressUnmanagedCodeSecurity]
793 public static byte ReadByte ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
795 throw new NotImplementedException ();
798 public unsafe static short ReadInt16 (IntPtr ptr)
800 byte *addr = (byte *) ptr;
802 // The mono JIT can't inline this due to the hight number of calls
803 // return ReadInt16 (ptr, 0);
805 if (((uint)addr & 1) == 0)
806 return *(short*)addr;
809 String.memcpy ((byte*)&s, (byte*)ptr, 2);
813 public unsafe static short ReadInt16 (IntPtr ptr, int ofs)
815 byte *addr = ((byte *) ptr) + ofs;
817 if (((uint) addr & 1) == 0)
818 return *(short*)addr;
821 String.memcpy ((byte*)&s, addr, 2);
826 [SuppressUnmanagedCodeSecurity]
827 public static short ReadInt16 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
829 throw new NotImplementedException ();
832 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
833 public unsafe static int ReadInt32 (IntPtr ptr)
835 byte *addr = (byte *) ptr;
837 if (((uint)addr & 3) == 0)
841 String.memcpy ((byte*)&s, addr, 4);
845 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
846 public unsafe static int ReadInt32 (IntPtr ptr, int ofs)
848 byte *addr = ((byte *) ptr) + ofs;
850 if ((((int) addr) & 3) == 0)
854 String.memcpy ((byte*)&s, addr, 4);
859 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
861 [SuppressUnmanagedCodeSecurity]
862 public static int ReadInt32 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
864 throw new NotImplementedException ();
867 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
868 public unsafe static long ReadInt64 (IntPtr ptr)
870 byte *addr = (byte *) ptr;
872 // The real alignment might be 4 on some platforms, but this is just an optimization,
873 // so it doesn't matter.
874 if (((uint) addr & 7) == 0)
878 String.memcpy ((byte*)&s, addr, 8);
882 public unsafe static long ReadInt64 (IntPtr ptr, int ofs)
884 byte *addr = ((byte *) ptr) + ofs;
886 if (((uint) addr & 7) == 0)
890 String.memcpy ((byte*)&s, addr, 8);
894 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
896 [SuppressUnmanagedCodeSecurity]
897 public static long ReadInt64 ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
899 throw new NotImplementedException ();
902 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
903 public static IntPtr ReadIntPtr (IntPtr ptr)
905 if (IntPtr.Size == 4)
906 return (IntPtr)ReadInt32 (ptr);
908 return (IntPtr)ReadInt64 (ptr);
911 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
912 public static IntPtr ReadIntPtr (IntPtr ptr, int ofs)
914 if (IntPtr.Size == 4)
915 return (IntPtr)ReadInt32 (ptr, ofs);
917 return (IntPtr)ReadInt64 (ptr, ofs);
920 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
922 public static IntPtr ReadIntPtr ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
924 throw new NotImplementedException ();
927 [MethodImplAttribute (MethodImplOptions.InternalCall)]
928 public extern static IntPtr ReAllocCoTaskMem (IntPtr pv, int cb);
930 [MethodImplAttribute(MethodImplOptions.InternalCall)]
931 public extern static IntPtr ReAllocHGlobal (IntPtr pv, IntPtr cb);
934 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
935 [MethodImplAttribute (MethodImplOptions.InternalCall)]
936 private extern static int ReleaseInternal (IntPtr pUnk);
939 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
940 public static int Release (IntPtr pUnk)
943 if (pUnk == IntPtr.Zero)
944 throw new ArgumentException ("Value cannot be null.", "pUnk");
946 return ReleaseInternal (pUnk);
948 throw new NotImplementedException ();
952 #if !FULL_AOT_RUNTIME
953 [MethodImplAttribute (MethodImplOptions.InternalCall)]
954 private extern static int ReleaseComObjectInternal (object co);
956 public static int ReleaseComObject (object o)
959 throw new ArgumentException ("Value cannot be null.", "o");
960 if (!IsComObject (o))
961 throw new ArgumentException ("Value must be a Com object.", "o");
962 return ReleaseComObjectInternal (o);
967 public static void ReleaseThreadCache()
969 throw new NotImplementedException ();
972 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
973 public static bool SetComObjectData (object obj, object key, object data)
975 throw new NotSupportedException ("MSDN states user code should never need to call this method.");
980 public static int SizeOf (object structure)
982 return SizeOf (structure.GetType ());
985 [MethodImplAttribute(MethodImplOptions.InternalCall)]
986 public extern static int SizeOf (Type t);
989 public static int SizeOf<T> () {
990 return SizeOf (typeof (T));
993 public static int SizeOf<T> (T structure) {
994 return SizeOf (structure.GetType ());
998 [MethodImplAttribute(MethodImplOptions.InternalCall)]
999 public extern static IntPtr StringToBSTR (string s);
1002 // I believe this is wrong, because in Mono and in P/Invoke
1003 // we treat "Ansi" conversions as UTF-8 conversions, while
1004 // this one does not do this
1006 public static IntPtr StringToCoTaskMemAnsi (string s)
1008 int length = s.Length + 1;
1009 IntPtr ctm = AllocCoTaskMem (length);
1011 byte[] asBytes = new byte[length];
1012 for (int i = 0; i < s.Length; i++)
1013 asBytes[i] = (byte)s[i];
1014 asBytes[s.Length] = 0;
1016 copy_to_unmanaged (asBytes, 0, ctm, length);
1020 public static IntPtr StringToCoTaskMemAuto (string s)
1022 return SystemDefaultCharSize == 2
1023 ? StringToCoTaskMemUni (s) : StringToCoTaskMemAnsi (s);
1026 public static IntPtr StringToCoTaskMemUni (string s)
1028 int length = s.Length + 1;
1029 IntPtr ctm = AllocCoTaskMem (length * 2);
1031 char[] asChars = new char[length];
1032 s.CopyTo (0, asChars, 0, s.Length);
1033 asChars[s.Length] = '\0';
1035 copy_to_unmanaged (asChars, 0, ctm, length);
1039 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1040 public extern static IntPtr StringToHGlobalAnsi (string s);
1042 public static IntPtr StringToHGlobalAuto (string s)
1044 return SystemDefaultCharSize == 2
1045 ? StringToHGlobalUni (s) : StringToHGlobalAnsi (s);
1048 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1049 public extern static IntPtr StringToHGlobalUni (string s);
1051 public static IntPtr SecureStringToBSTR (SecureString s)
1054 throw new ArgumentNullException ("s");
1056 IntPtr ctm = AllocCoTaskMem ((len+1) * 2 + 4);
1057 byte [] buffer = null;
1058 WriteInt32 (ctm, 0, len*2);
1060 buffer = s.GetBuffer ();
1062 for (int i = 0; i < len; i++)
1063 WriteInt16 (ctm, 4 + (i * 2), (short) ((buffer [(i*2)] << 8) | (buffer [i*2+1])));
1064 WriteInt16 (ctm, 4 + buffer.Length, 0);
1067 for (int i = buffer.Length; i > 0; ){
1072 return (IntPtr) ((long)ctm + 4);
1075 public static IntPtr SecureStringToCoTaskMemAnsi (SecureString s)
1078 throw new ArgumentNullException ("s");
1080 IntPtr ctm = AllocCoTaskMem (len + 1);
1081 byte [] copy = new byte [len+1];
1084 byte [] buffer = s.GetBuffer ();
1086 for (; i < len; i++, j += 2){
1087 copy [i] = buffer [j+1];
1092 copy_to_unmanaged (copy, 0, ctm, len+1);
1094 // Ensure that we clear the buffer.
1095 for (int i = len; i > 0; ){
1103 public static IntPtr SecureStringToCoTaskMemUnicode (SecureString s)
1106 throw new ArgumentNullException ("s");
1108 IntPtr ctm = AllocCoTaskMem (len * 2 + 2);
1109 byte [] buffer = null;
1111 buffer = s.GetBuffer ();
1112 for (int i = 0; i < len; i++)
1113 WriteInt16 (ctm, i * 2, (short) ((buffer [(i*2)] << 8) | (buffer [i*2+1])));
1114 WriteInt16 (ctm, buffer.Length, 0);
1117 for (int i = buffer.Length; i > 0; ){
1125 public static IntPtr SecureStringToGlobalAllocAnsi (SecureString s)
1128 throw new ArgumentNullException ("s");
1129 return SecureStringToCoTaskMemAnsi (s);
1132 public static IntPtr SecureStringToGlobalAllocUnicode (SecureString s)
1135 throw new ArgumentNullException ("s");
1136 return SecureStringToCoTaskMemUnicode (s);
1139 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
1141 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1142 public extern static void StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld);
1145 public static void StructureToPtr<T> (T structure, IntPtr ptr, bool fDeleteOld) {
1146 StructureToPtr ((object)structure, ptr, fDeleteOld);
1150 public static void ThrowExceptionForHR (int errorCode) {
1151 Exception ex = GetExceptionForHR (errorCode);
1156 public static void ThrowExceptionForHR (int errorCode, IntPtr errorInfo) {
1157 Exception ex = GetExceptionForHR (errorCode, errorInfo);
1162 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1163 public extern static IntPtr UnsafeAddrOfPinnedArrayElement (Array arr, int index);
1166 public static IntPtr UnsafeAddrOfPinnedArrayElement<T> (T[] arr, int index) {
1167 return UnsafeAddrOfPinnedArrayElement ((Array)arr, index);
1171 public static void WriteByte (IntPtr ptr, byte val)
1178 public static void WriteByte (IntPtr ptr, int ofs, byte val) {
1180 *(byte*)(IntPtr.Add (ptr, ofs)) = val;
1185 [SuppressUnmanagedCodeSecurity]
1186 public static void WriteByte ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, byte val)
1188 throw new NotImplementedException ();
1191 public static unsafe void WriteInt16 (IntPtr ptr, short val)
1193 byte *addr = (byte *) ptr;
1195 if (((uint)addr & 1) == 0)
1196 *(short*)addr = val;
1198 String.memcpy (addr, (byte*)&val, 2);
1201 public static unsafe void WriteInt16 (IntPtr ptr, int ofs, short val)
1203 byte *addr = ((byte *) ptr) + ofs;
1205 if (((uint)addr & 1) == 0)
1206 *(short*)addr = val;
1208 String.memcpy (addr, (byte*)&val, 2);
1213 [SuppressUnmanagedCodeSecurity]
1214 public static void WriteInt16 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, short val)
1216 throw new NotImplementedException ();
1219 public static void WriteInt16 (IntPtr ptr, char val)
1221 WriteInt16 (ptr, 0, (short)val);
1224 public static void WriteInt16 (IntPtr ptr, int ofs, char val)
1226 WriteInt16 (ptr, ofs, (short)val);
1230 public static void WriteInt16([In, Out] object ptr, int ofs, char val)
1232 throw new NotImplementedException ();
1235 public static unsafe void WriteInt32 (IntPtr ptr, int val)
1237 byte *addr = (byte *) ptr;
1239 if (((uint)addr & 3) == 0)
1242 String.memcpy (addr, (byte*)&val, 4);
1246 public unsafe static void WriteInt32 (IntPtr ptr, int ofs, int val)
1248 byte *addr = ((byte *) ptr) + ofs;
1250 if (((uint)addr & 3) == 0)
1253 String.memcpy (addr, (byte*)&val, 4);
1258 [SuppressUnmanagedCodeSecurity]
1259 public static void WriteInt32([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, int val)
1261 throw new NotImplementedException ();
1264 public static unsafe void WriteInt64 (IntPtr ptr, long val)
1266 byte *addr = (byte *) ptr;
1268 // The real alignment might be 4 on some platforms, but this is just an optimization,
1269 // so it doesn't matter.
1270 if (((uint)addr & 7) == 0)
1273 String.memcpy (addr, (byte*)&val, 8);
1276 public static unsafe void WriteInt64 (IntPtr ptr, int ofs, long val)
1278 byte *addr = ((byte *) ptr) + ofs;
1280 // The real alignment might be 4 on some platforms, but this is just an optimization,
1281 // so it doesn't matter.
1282 if (((uint)addr & 7) == 0)
1285 String.memcpy (addr, (byte*)&val, 8);
1289 [SuppressUnmanagedCodeSecurity]
1290 public static void WriteInt64 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, long val)
1292 throw new NotImplementedException ();
1295 public static void WriteIntPtr (IntPtr ptr, IntPtr val)
1297 if (IntPtr.Size == 4)
1298 WriteInt32 (ptr, (int)val);
1300 WriteInt64 (ptr, (long)val);
1303 public static void WriteIntPtr (IntPtr ptr, int ofs, IntPtr val)
1305 if (IntPtr.Size == 4)
1306 WriteInt32 (ptr, ofs, (int)val);
1308 WriteInt64 (ptr, ofs, (long)val);
1312 public static void WriteIntPtr([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, IntPtr val)
1314 throw new NotImplementedException ();
1317 public static Exception GetExceptionForHR (int errorCode) {
1318 return GetExceptionForHR (errorCode, IntPtr.Zero);
1321 public static Exception GetExceptionForHR (int errorCode, IntPtr errorInfo) {
1323 const int E_OUTOFMEMORY = unchecked ((int)0x8007000EL);
1324 const int E_INVALIDARG = unchecked ((int)0X80070057);
1329 return new OutOfMemoryException ();
1331 return new ArgumentException ();
1334 return new COMException ("", errorCode);
1338 #if !FULL_AOT_RUNTIME
1339 public static int FinalReleaseComObject (object o)
1341 while (ReleaseComObject (o) != 0);
1346 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1347 private static extern Delegate GetDelegateForFunctionPointerInternal (IntPtr ptr, Type t);
1349 public static Delegate GetDelegateForFunctionPointer (IntPtr ptr, Type t)
1352 throw new ArgumentNullException ("t");
1353 if (!t.IsSubclassOf (typeof (MulticastDelegate)) || (t == typeof (MulticastDelegate)))
1354 throw new ArgumentException ("Type is not a delegate", "t");
1355 if (t.IsGenericType)
1356 throw new ArgumentException ("The specified Type must not be a generic type definition.");
1357 if (ptr == IntPtr.Zero)
1358 throw new ArgumentNullException ("ptr");
1360 return GetDelegateForFunctionPointerInternal (ptr, t);
1364 public static TDelegate GetDelegateForFunctionPointer<TDelegate> (IntPtr ptr) {
1365 return (TDelegate) (object) GetDelegateForFunctionPointer (ptr, typeof (TDelegate));
1369 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1370 private static extern IntPtr GetFunctionPointerForDelegateInternal (Delegate d);
1372 public static IntPtr GetFunctionPointerForDelegate (Delegate d)
1375 throw new ArgumentNullException ("d");
1377 return GetFunctionPointerForDelegateInternal (d);
1381 public static IntPtr GetFunctionPointerForDelegate<TDelegate> (TDelegate d) {
1383 throw new ArgumentNullException ("d");
1385 return GetFunctionPointerForDelegateInternal ((Delegate)(object)d);