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 ();
190 #if !FULL_AOT_RUNTIME
191 public static object CreateWrapperOfType (object o, Type t)
193 __ComObject co = o as __ComObject;
195 throw new ArgumentException ("o must derive from __ComObject", "o");
197 throw new ArgumentNullException ("t");
199 Type[] itfs = o.GetType ().GetInterfaces ();
200 foreach (Type itf in itfs) {
201 if (itf.IsImport && co.GetInterface (itf) == IntPtr.Zero)
202 throw new InvalidCastException ();
205 return ComInteropProxy.GetProxy (co.IUnknown, t).GetTransparentProxy ();
209 [MethodImplAttribute(MethodImplOptions.InternalCall)]
211 public extern static void DestroyStructure (IntPtr ptr, Type structuretype);
213 [MethodImplAttribute(MethodImplOptions.InternalCall)]
214 public extern static void FreeBSTR (IntPtr ptr);
216 [MethodImplAttribute(MethodImplOptions.InternalCall)]
217 public extern static void FreeCoTaskMem (IntPtr ptr);
219 [MethodImplAttribute(MethodImplOptions.InternalCall)]
220 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
221 public extern static void FreeHGlobal (IntPtr hglobal);
223 static void ClearBSTR (IntPtr ptr)
225 int len = ReadInt32 (ptr, -4);
227 for (int i = 0; i < len; i++)
228 WriteByte (ptr, i, 0);
231 public static void ZeroFreeBSTR (IntPtr s)
237 static void ClearAnsi (IntPtr ptr)
239 for (int i = 0; ReadByte (ptr, i) != 0; i++)
240 WriteByte (ptr, i, 0);
243 static void ClearUnicode (IntPtr ptr)
245 for (int i = 0; ReadInt16 (ptr, i) != 0; i += 2)
246 WriteInt16 (ptr, i, 0);
249 public static void ZeroFreeCoTaskMemAnsi (IntPtr s)
255 public static void ZeroFreeCoTaskMemUnicode (IntPtr s)
261 public static void ZeroFreeGlobalAllocAnsi (IntPtr s)
267 public static void ZeroFreeGlobalAllocUnicode (IntPtr s)
273 #if !FULL_AOT_RUNTIME
274 public static Guid GenerateGuidForType (Type type)
279 public static string GenerateProgIdForType (Type type)
281 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (type);
283 foreach (var a in attrs)
285 var dt = a.Constructor.DeclaringType;
286 string name = dt.Name;
287 if (name == "ProgIdAttribute")
289 var args = a.ConstructorArguments;
290 string text = a.ConstructorArguments[0].Value as string;
299 return type.FullName;
303 public static object GetActiveObject (string progID)
305 throw new NotImplementedException ();
309 [MethodImplAttribute (MethodImplOptions.InternalCall)]
310 private extern static IntPtr GetCCW (object o, Type T);
312 private static IntPtr GetComInterfaceForObjectInternal (object o, Type T)
315 return ((__ComObject)o).GetInterface (T);
317 return GetCCW (o, T);
321 public static IntPtr GetComInterfaceForObject (object o, Type T)
324 IntPtr pItf = GetComInterfaceForObjectInternal (o, T);
328 throw new NotImplementedException ();
333 public static IntPtr GetComInterfaceForObjectInContext (object o, Type t)
335 throw new NotImplementedException ();
338 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
339 public static object GetComObjectData (object obj, object key)
341 throw new NotSupportedException ("MSDN states user code should never need to call this method.");
345 [MethodImplAttribute(MethodImplOptions.InternalCall)]
346 private extern static int GetComSlotForMethodInfoInternal (MemberInfo m);
349 public static int GetComSlotForMethodInfo (MemberInfo m)
353 throw new ArgumentNullException ("m");
354 if (!(m is MethodInfo))
355 throw new ArgumentException ("The MemberInfo must be an interface method.", "m");
356 if (!m.DeclaringType.IsInterface)
357 throw new ArgumentException ("The MemberInfo must be an interface method.", "m");
358 return GetComSlotForMethodInfoInternal (m);
360 throw new NotImplementedException ();
365 public static int GetEndComSlot (Type t)
367 throw new NotImplementedException ();
371 public static int GetExceptionCode()
373 throw new NotImplementedException ();
378 public static IntPtr GetExceptionPointers()
380 throw new NotImplementedException ();
383 public static IntPtr GetHINSTANCE (Module m)
386 throw new ArgumentNullException ("m");
388 return m.GetHINSTANCE ();
390 #endif // !FULL_AOT_RUNTIME
392 #if !FULL_AOT_RUNTIME
393 [MonoTODO ("SetErrorInfo")]
394 public static int GetHRForException (Exception e)
400 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
401 public static int GetHRForLastWin32Error()
403 throw new NotImplementedException ();
406 [MethodImplAttribute (MethodImplOptions.InternalCall)]
407 private extern static IntPtr GetIDispatchForObjectInternal (object o);
409 public static IntPtr GetIDispatchForObject (object o)
411 IntPtr pUnk = GetIDispatchForObjectInternal (o);
412 // Internal method does not AddRef
418 public static IntPtr GetIDispatchForObjectInContext (object o)
420 throw new NotImplementedException ();
424 public static IntPtr GetITypeInfoForType (Type t)
426 throw new NotImplementedException ();
429 [MethodImplAttribute (MethodImplOptions.InternalCall)]
430 private extern static IntPtr GetIUnknownForObjectInternal (object o);
432 public static IntPtr GetIUnknownForObject (object o)
434 IntPtr pUnk = GetIUnknownForObjectInternal (o);
435 // Internal method does not AddRef
441 public static IntPtr GetIUnknownForObjectInContext (object o)
443 throw new NotImplementedException ();
447 [Obsolete ("This method has been deprecated")]
448 public static IntPtr GetManagedThunkForUnmanagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
450 throw new NotImplementedException ();
454 public static MemberInfo GetMethodInfoForComSlot (Type t, int slot, ref ComMemberType memberType)
456 throw new NotImplementedException ();
459 public static void GetNativeVariantForObject (object obj, IntPtr pDstNativeVariant)
461 Variant vt = new Variant();
463 Marshal.StructureToPtr(vt, pDstNativeVariant, false);
467 [MethodImplAttribute (MethodImplOptions.InternalCall)]
468 private static extern object GetObjectForCCW (IntPtr pUnk);
471 public static object GetObjectForIUnknown (IntPtr pUnk)
474 object obj = GetObjectForCCW (pUnk);
477 ComInteropProxy proxy = ComInteropProxy.GetProxy (pUnk, typeof (__ComObject));
478 obj = proxy.GetTransparentProxy ();
482 throw new NotImplementedException ();
486 public static object GetObjectForNativeVariant (IntPtr pSrcNativeVariant)
488 Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
489 return vt.GetValue();
492 public static object[] GetObjectsForNativeVariants (IntPtr aSrcNativeVariant, int cVars)
495 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
496 object[] objects = new object[cVars];
497 for (int i = 0; i < cVars; i++)
498 objects[i] = GetObjectForNativeVariant ((IntPtr)(aSrcNativeVariant.ToInt64 () +
499 i * SizeOf (typeof(Variant))));
504 public static int GetStartComSlot (Type t)
506 throw new NotImplementedException ();
510 [Obsolete ("This method has been deprecated")]
511 public static Thread GetThreadFromFiberCookie (int cookie)
513 throw new NotImplementedException ();
516 public static object GetTypedObjectForIUnknown (IntPtr pUnk, Type t)
518 ComInteropProxy proxy = new ComInteropProxy (pUnk, t);
519 __ComObject co = (__ComObject)proxy.GetTransparentProxy ();
520 foreach (Type itf in t.GetInterfaces ()) {
521 if ((itf.Attributes & TypeAttributes.Import) == TypeAttributes.Import) {
522 if (co.GetInterface (itf) == IntPtr.Zero)
530 public static Type GetTypeForITypeInfo (IntPtr piTypeInfo)
532 throw new NotImplementedException ();
535 #if !FULL_AOT_RUNTIME
538 public static string GetTypeInfoName (UCOMITypeInfo pTI)
540 throw new NotImplementedException ();
543 public static string GetTypeInfoName (ITypeInfo typeInfo)
545 throw new NotImplementedException ();
550 public static Guid GetTypeLibGuid (UCOMITypeLib pTLB)
552 throw new NotImplementedException ();
556 public static Guid GetTypeLibGuid (ITypeLib typelib)
558 throw new NotImplementedException ();
562 public static Guid GetTypeLibGuidForAssembly (Assembly asm)
564 throw new NotImplementedException ();
569 public static int GetTypeLibLcid (UCOMITypeLib pTLB)
571 throw new NotImplementedException ();
575 public static int GetTypeLibLcid (ITypeLib typelib)
577 throw new NotImplementedException ();
582 public static string GetTypeLibName (UCOMITypeLib pTLB)
584 throw new NotImplementedException ();
588 public static string GetTypeLibName (ITypeLib typelib)
590 throw new NotImplementedException ();
594 public static void GetTypeLibVersionForAssembly (Assembly inputAssembly, out int majorVersion, out int minorVersion)
596 throw new NotImplementedException ();
599 public static object GetUniqueObjectForIUnknown (IntPtr unknown)
601 throw new NotImplementedException ();
606 [Obsolete ("This method has been deprecated")]
607 public static IntPtr GetUnmanagedThunkForManagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
609 throw new NotImplementedException ();
613 [MethodImplAttribute (MethodImplOptions.InternalCall)]
614 public extern static bool IsComObject (object o);
616 public static bool IsComObject (object o)
618 throw new NotImplementedException ();
623 public static bool IsTypeVisibleFromCom (Type t)
625 throw new NotImplementedException ();
629 public static int NumParamBytes (MethodInfo m)
631 throw new NotImplementedException ();
635 [MethodImplAttribute(MethodImplOptions.InternalCall)]
636 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
637 public static extern int GetLastWin32Error();
639 [MethodImplAttribute(MethodImplOptions.InternalCall)]
640 public extern static IntPtr OffsetOf (Type t, string fieldName);
642 [MethodImplAttribute(MethodImplOptions.InternalCall)]
643 public extern static void Prelink (MethodInfo m);
645 [MethodImplAttribute(MethodImplOptions.InternalCall)]
646 public extern static void PrelinkAll (Type c);
648 [MethodImplAttribute(MethodImplOptions.InternalCall)]
649 public extern static string PtrToStringAnsi (IntPtr ptr);
651 [MethodImplAttribute(MethodImplOptions.InternalCall)]
652 public extern static string PtrToStringAnsi (IntPtr ptr, int len);
654 public static string PtrToStringAuto (IntPtr ptr)
656 return SystemDefaultCharSize == 2
657 ? PtrToStringUni (ptr) : PtrToStringAnsi (ptr);
660 public static string PtrToStringAuto (IntPtr ptr, int len)
662 return SystemDefaultCharSize == 2
663 ? PtrToStringUni (ptr, len) : PtrToStringAnsi (ptr, len);
666 [MethodImplAttribute(MethodImplOptions.InternalCall)]
667 public extern static string PtrToStringUni (IntPtr ptr);
669 [MethodImplAttribute(MethodImplOptions.InternalCall)]
670 public extern static string PtrToStringUni (IntPtr ptr, int len);
673 [MethodImplAttribute(MethodImplOptions.InternalCall)]
674 public extern static string PtrToStringBSTR (IntPtr ptr);
676 public static string PtrToStringBSTR (IntPtr ptr)
678 throw new NotImplementedException ();
682 [MethodImplAttribute(MethodImplOptions.InternalCall)]
684 public extern static void PtrToStructure (IntPtr ptr, object structure);
686 [MethodImplAttribute(MethodImplOptions.InternalCall)]
688 public extern static object PtrToStructure (IntPtr ptr, Type structureType);
691 [MethodImplAttribute (MethodImplOptions.InternalCall)]
692 private extern static int QueryInterfaceInternal (IntPtr pUnk, ref Guid iid, out IntPtr ppv);
695 public static int QueryInterface (IntPtr pUnk, ref Guid iid, out IntPtr ppv)
698 if (pUnk == IntPtr.Zero)
699 throw new ArgumentException ("Value cannot be null.", "pUnk");
700 return QueryInterfaceInternal (pUnk, ref iid, out ppv);
702 throw new NotImplementedException ();
706 public static byte ReadByte (IntPtr ptr)
713 public static byte ReadByte (IntPtr ptr, int ofs) {
715 return *((byte*)ptr + ofs);
720 [SuppressUnmanagedCodeSecurity]
721 public static byte ReadByte ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
723 throw new NotImplementedException ();
726 public unsafe static short ReadInt16 (IntPtr ptr)
728 byte *addr = (byte *) ptr;
730 // The mono JIT can't inline this due to the hight number of calls
731 // return ReadInt16 (ptr, 0);
733 if (((uint)addr & 1) == 0)
734 return *(short*)addr;
737 String.memcpy ((byte*)&s, (byte*)ptr, 2);
741 public unsafe static short ReadInt16 (IntPtr ptr, int ofs)
743 byte *addr = ((byte *) ptr) + ofs;
745 if (((uint) addr & 1) == 0)
746 return *(short*)addr;
749 String.memcpy ((byte*)&s, addr, 2);
754 [SuppressUnmanagedCodeSecurity]
755 public static short ReadInt16 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
757 throw new NotImplementedException ();
760 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
761 public unsafe static int ReadInt32 (IntPtr ptr)
763 byte *addr = (byte *) ptr;
765 if (((uint)addr & 3) == 0)
769 String.memcpy ((byte*)&s, addr, 4);
773 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
774 public unsafe static int ReadInt32 (IntPtr ptr, int ofs)
776 byte *addr = ((byte *) ptr) + ofs;
778 if ((((int) addr) & 3) == 0)
782 String.memcpy ((byte*)&s, addr, 4);
787 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
789 [SuppressUnmanagedCodeSecurity]
790 public static int ReadInt32 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
792 throw new NotImplementedException ();
795 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
796 public unsafe static long ReadInt64 (IntPtr ptr)
798 byte *addr = (byte *) ptr;
800 // The real alignment might be 4 on some platforms, but this is just an optimization,
801 // so it doesn't matter.
802 if (((uint) addr & 7) == 0)
806 String.memcpy ((byte*)&s, addr, 8);
810 public unsafe static long ReadInt64 (IntPtr ptr, int ofs)
812 byte *addr = ((byte *) ptr) + ofs;
814 if (((uint) addr & 7) == 0)
818 String.memcpy ((byte*)&s, addr, 8);
822 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
824 [SuppressUnmanagedCodeSecurity]
825 public static long ReadInt64 ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
827 throw new NotImplementedException ();
830 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
831 public static IntPtr ReadIntPtr (IntPtr ptr)
833 if (IntPtr.Size == 4)
834 return (IntPtr)ReadInt32 (ptr);
836 return (IntPtr)ReadInt64 (ptr);
839 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
840 public static IntPtr ReadIntPtr (IntPtr ptr, int ofs)
842 if (IntPtr.Size == 4)
843 return (IntPtr)ReadInt32 (ptr, ofs);
845 return (IntPtr)ReadInt64 (ptr, ofs);
848 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
850 public static IntPtr ReadIntPtr ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
852 throw new NotImplementedException ();
855 [MethodImplAttribute (MethodImplOptions.InternalCall)]
856 public extern static IntPtr ReAllocCoTaskMem (IntPtr pv, int cb);
858 [MethodImplAttribute(MethodImplOptions.InternalCall)]
859 public extern static IntPtr ReAllocHGlobal (IntPtr pv, IntPtr cb);
862 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
863 [MethodImplAttribute (MethodImplOptions.InternalCall)]
864 private extern static int ReleaseInternal (IntPtr pUnk);
867 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
868 public static int Release (IntPtr pUnk)
871 if (pUnk == IntPtr.Zero)
872 throw new ArgumentException ("Value cannot be null.", "pUnk");
874 return ReleaseInternal (pUnk);
876 throw new NotImplementedException ();
880 #if !FULL_AOT_RUNTIME
881 [MethodImplAttribute (MethodImplOptions.InternalCall)]
882 private extern static int ReleaseComObjectInternal (object co);
884 public static int ReleaseComObject (object o)
887 throw new ArgumentException ("Value cannot be null.", "o");
888 if (!IsComObject (o))
889 throw new ArgumentException ("Value must be a Com object.", "o");
890 return ReleaseComObjectInternal (o);
895 public static void ReleaseThreadCache()
897 throw new NotImplementedException ();
900 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
901 public static bool SetComObjectData (object obj, object key, object data)
903 throw new NotSupportedException ("MSDN states user code should never need to call this method.");
908 public static int SizeOf (object structure)
910 return SizeOf (structure.GetType ());
913 [MethodImplAttribute(MethodImplOptions.InternalCall)]
914 public extern static int SizeOf (Type t);
916 [MethodImplAttribute(MethodImplOptions.InternalCall)]
917 public extern static IntPtr StringToBSTR (string s);
920 // I believe this is wrong, because in Mono and in P/Invoke
921 // we treat "Ansi" conversions as UTF-8 conversions, while
922 // this one does not do this
924 public static IntPtr StringToCoTaskMemAnsi (string s)
926 int length = s.Length + 1;
927 IntPtr ctm = AllocCoTaskMem (length);
929 byte[] asBytes = new byte[length];
930 for (int i = 0; i < s.Length; i++)
931 asBytes[i] = (byte)s[i];
932 asBytes[s.Length] = 0;
934 copy_to_unmanaged (asBytes, 0, ctm, length);
938 public static IntPtr StringToCoTaskMemAuto (string s)
940 return SystemDefaultCharSize == 2
941 ? StringToCoTaskMemUni (s) : StringToCoTaskMemAnsi (s);
944 public static IntPtr StringToCoTaskMemUni (string s)
946 int length = s.Length + 1;
947 IntPtr ctm = AllocCoTaskMem (length * 2);
949 char[] asChars = new char[length];
950 s.CopyTo (0, asChars, 0, s.Length);
951 asChars[s.Length] = '\0';
953 copy_to_unmanaged (asChars, 0, ctm, length);
957 [MethodImplAttribute(MethodImplOptions.InternalCall)]
958 public extern static IntPtr StringToHGlobalAnsi (string s);
960 public static IntPtr StringToHGlobalAuto (string s)
962 return SystemDefaultCharSize == 2
963 ? StringToHGlobalUni (s) : StringToHGlobalAnsi (s);
966 [MethodImplAttribute(MethodImplOptions.InternalCall)]
967 public extern static IntPtr StringToHGlobalUni (string s);
969 public static IntPtr SecureStringToBSTR (SecureString s)
972 throw new ArgumentNullException ("s");
974 IntPtr ctm = AllocCoTaskMem ((len+1) * 2 + 4);
975 byte [] buffer = null;
976 WriteInt32 (ctm, 0, len*2);
978 buffer = s.GetBuffer ();
980 for (int i = 0; i < len; i++)
981 WriteInt16 (ctm, 4 + (i * 2), (short) ((buffer [(i*2)] << 8) | (buffer [i*2+1])));
982 WriteInt16 (ctm, 4 + buffer.Length, 0);
985 for (int i = buffer.Length; i > 0; ){
990 return (IntPtr) ((long)ctm + 4);
993 public static IntPtr SecureStringToCoTaskMemAnsi (SecureString s)
996 throw new ArgumentNullException ("s");
998 IntPtr ctm = AllocCoTaskMem (len + 1);
999 byte [] copy = new byte [len+1];
1002 byte [] buffer = s.GetBuffer ();
1004 for (; i < len; i++, j += 2){
1005 copy [i] = buffer [j+1];
1010 copy_to_unmanaged (copy, 0, ctm, len+1);
1012 // Ensure that we clear the buffer.
1013 for (int i = len; i > 0; ){
1021 public static IntPtr SecureStringToCoTaskMemUnicode (SecureString s)
1024 throw new ArgumentNullException ("s");
1026 IntPtr ctm = AllocCoTaskMem (len * 2 + 2);
1027 byte [] buffer = null;
1029 buffer = s.GetBuffer ();
1030 for (int i = 0; i < len; i++)
1031 WriteInt16 (ctm, i * 2, (short) ((buffer [(i*2)] << 8) | (buffer [i*2+1])));
1032 WriteInt16 (ctm, buffer.Length, 0);
1035 for (int i = buffer.Length; i > 0; ){
1043 public static IntPtr SecureStringToGlobalAllocAnsi (SecureString s)
1046 throw new ArgumentNullException ("s");
1047 return SecureStringToCoTaskMemAnsi (s);
1050 public static IntPtr SecureStringToGlobalAllocUnicode (SecureString s)
1053 throw new ArgumentNullException ("s");
1054 return SecureStringToCoTaskMemUnicode (s);
1057 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
1059 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1060 public extern static void StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld);
1062 public static void ThrowExceptionForHR (int errorCode) {
1063 Exception ex = GetExceptionForHR (errorCode);
1068 public static void ThrowExceptionForHR (int errorCode, IntPtr errorInfo) {
1069 Exception ex = GetExceptionForHR (errorCode, errorInfo);
1074 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1075 public extern static IntPtr UnsafeAddrOfPinnedArrayElement (Array arr, int index);
1077 public static void WriteByte (IntPtr ptr, byte val)
1084 public static void WriteByte (IntPtr ptr, int ofs, byte val) {
1086 *(byte*)(IntPtr.Add (ptr, ofs)) = val;
1091 [SuppressUnmanagedCodeSecurity]
1092 public static void WriteByte ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, byte val)
1094 throw new NotImplementedException ();
1097 public static unsafe void WriteInt16 (IntPtr ptr, short val)
1099 byte *addr = (byte *) ptr;
1101 if (((uint)addr & 1) == 0)
1102 *(short*)addr = val;
1104 String.memcpy (addr, (byte*)&val, 2);
1107 public static unsafe void WriteInt16 (IntPtr ptr, int ofs, short val)
1109 byte *addr = ((byte *) ptr) + ofs;
1111 if (((uint)addr & 1) == 0)
1112 *(short*)addr = val;
1114 String.memcpy (addr, (byte*)&val, 2);
1119 [SuppressUnmanagedCodeSecurity]
1120 public static void WriteInt16 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, short val)
1122 throw new NotImplementedException ();
1125 public static void WriteInt16 (IntPtr ptr, char val)
1127 WriteInt16 (ptr, 0, (short)val);
1130 public static void WriteInt16 (IntPtr ptr, int ofs, char val)
1132 WriteInt16 (ptr, ofs, (short)val);
1136 public static void WriteInt16([In, Out] object ptr, int ofs, char val)
1138 throw new NotImplementedException ();
1141 public static unsafe void WriteInt32 (IntPtr ptr, int val)
1143 byte *addr = (byte *) ptr;
1145 if (((uint)addr & 3) == 0)
1148 String.memcpy (addr, (byte*)&val, 4);
1152 public unsafe static void WriteInt32 (IntPtr ptr, int ofs, int val)
1154 byte *addr = ((byte *) ptr) + ofs;
1156 if (((uint)addr & 3) == 0)
1159 String.memcpy (addr, (byte*)&val, 4);
1164 [SuppressUnmanagedCodeSecurity]
1165 public static void WriteInt32([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, int val)
1167 throw new NotImplementedException ();
1170 public static unsafe void WriteInt64 (IntPtr ptr, long val)
1172 byte *addr = (byte *) ptr;
1174 // The real alignment might be 4 on some platforms, but this is just an optimization,
1175 // so it doesn't matter.
1176 if (((uint)addr & 7) == 0)
1179 String.memcpy (addr, (byte*)&val, 8);
1182 public static unsafe void WriteInt64 (IntPtr ptr, int ofs, long val)
1184 byte *addr = ((byte *) ptr) + ofs;
1186 // The real alignment might be 4 on some platforms, but this is just an optimization,
1187 // so it doesn't matter.
1188 if (((uint)addr & 7) == 0)
1191 String.memcpy (addr, (byte*)&val, 8);
1195 [SuppressUnmanagedCodeSecurity]
1196 public static void WriteInt64 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, long val)
1198 throw new NotImplementedException ();
1201 public static void WriteIntPtr (IntPtr ptr, IntPtr val)
1203 if (IntPtr.Size == 4)
1204 WriteInt32 (ptr, (int)val);
1206 WriteInt64 (ptr, (long)val);
1209 public static void WriteIntPtr (IntPtr ptr, int ofs, IntPtr val)
1211 if (IntPtr.Size == 4)
1212 WriteInt32 (ptr, ofs, (int)val);
1214 WriteInt64 (ptr, ofs, (long)val);
1218 public static void WriteIntPtr([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, IntPtr val)
1220 throw new NotImplementedException ();
1223 public static Exception GetExceptionForHR (int errorCode) {
1224 return GetExceptionForHR (errorCode, IntPtr.Zero);
1227 public static Exception GetExceptionForHR (int errorCode, IntPtr errorInfo) {
1229 const int E_OUTOFMEMORY = unchecked ((int)0x8007000EL);
1230 const int E_INVALIDARG = unchecked ((int)0X80070057);
1235 return new OutOfMemoryException ();
1237 return new ArgumentException ();
1240 return new COMException ("", errorCode);
1244 #if !FULL_AOT_RUNTIME
1245 public static int FinalReleaseComObject (object o)
1247 while (ReleaseComObject (o) != 0);
1252 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1253 private static extern Delegate GetDelegateForFunctionPointerInternal (IntPtr ptr, Type t);
1255 public static Delegate GetDelegateForFunctionPointer (IntPtr ptr, Type t)
1258 throw new ArgumentNullException ("t");
1259 if (!t.IsSubclassOf (typeof (MulticastDelegate)) || (t == typeof (MulticastDelegate)))
1260 throw new ArgumentException ("Type is not a delegate", "t");
1261 if (t.IsGenericType)
1262 throw new ArgumentException ("The specified Type must not be a generic type definition.");
1263 if (ptr == IntPtr.Zero)
1264 throw new ArgumentNullException ("ptr");
1266 return GetDelegateForFunctionPointerInternal (ptr, t);
1269 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1270 private static extern IntPtr GetFunctionPointerForDelegateInternal (Delegate d);
1272 public static IntPtr GetFunctionPointerForDelegate (Delegate d)
1275 throw new ArgumentNullException ("d");
1277 return GetFunctionPointerForDelegateInternal (d);