Merge pull request #3436 from ntherning/fix-alt-dir-separator-not-replaced-in-Path...
[mono.git] / mcs / class / corlib / System.Runtime.InteropServices / Marshal.cs
1 // System.Runtime.InteropServices.Marshal.cs
2 //
3 // Sean MacIsaac (macisaac@ximian.com)
4 // Paolo Molaro (lupus@ximian.com)
5 // Dietmar Maurer (dietmar@ximian.com)
6 // Jonathan Chambers (joncham@gmail.com)
7 //
8 // (C) 2001-2002 Ximian, Inc.
9
10 //
11 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
12 //
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:
20 // 
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
23 // 
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.
31 //
32
33 using System.Collections;
34 using System.Collections.Generic;
35 using System.Runtime.CompilerServices;
36 using System;
37 using System.Security;
38 using System.Reflection;
39 using System.Threading;
40 using System.Runtime.InteropServices.ComTypes;
41
42 using System.Runtime.ConstrainedExecution;
43 #if !FULL_AOT_RUNTIME
44 using Mono.Interop;
45 #endif
46
47 namespace System.Runtime.InteropServices
48 {
49         public static class Marshal
50         {
51                 /* fields */
52                 public static readonly int SystemMaxDBCSCharSize = 2; // don't know what this is
53                 public static readonly int SystemDefaultCharSize = Environment.IsRunningOnWindows ? 2 : 1;
54
55 #if !MOBILE
56                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
57                 private extern static int AddRefInternal (IntPtr pUnk);
58 #endif
59
60                 public static int AddRef (IntPtr pUnk)
61                 {
62 #if !MOBILE
63                         if (pUnk == IntPtr.Zero)
64                                 throw new ArgumentException ("Value cannot be null.", "pUnk");
65                         return AddRefInternal (pUnk);
66 #else
67                         throw new NotImplementedException ();
68 #endif
69                 }
70
71                 [MonoTODO]
72                 public static bool AreComObjectsAvailableForCleanup ()
73                 {
74                         return false;
75                 }
76
77                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
78                 public extern static IntPtr AllocCoTaskMem (int cb);
79
80                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
81                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
82                 public extern static IntPtr AllocHGlobal (IntPtr cb);
83
84                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
85                 public static IntPtr AllocHGlobal (int cb)
86                 {
87                         return AllocHGlobal ((IntPtr)cb);
88                 }
89
90                 [MonoTODO]
91                 public static object BindToMoniker (string monikerName)
92                 {
93                         throw new NotImplementedException ();
94                 }
95
96                 [MonoTODO]
97                 public static void ChangeWrapperHandleStrength (object otp, bool fIsWeak)
98                 {
99                         throw new NotImplementedException ();
100                 }
101
102                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
103                 internal extern static void copy_to_unmanaged (Array source, int startIndex,
104                                                                IntPtr destination, int length);
105
106                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
107                 internal extern static void copy_from_unmanaged (IntPtr source, int startIndex,
108                                                                  Array destination, int length);
109
110                 public static void Copy (byte[] source, int startIndex, IntPtr destination, int length)
111                 {
112                         copy_to_unmanaged (source, startIndex, destination, length);
113                 }
114
115                 public static void Copy (char[] source, int startIndex, IntPtr destination, int length)
116                 {
117                         copy_to_unmanaged (source, startIndex, destination, length);
118                 }
119
120                 public static void Copy (short[] source, int startIndex, IntPtr destination, int length)
121                 {
122                         copy_to_unmanaged (source, startIndex, destination, length);
123                 }
124
125                 public static void Copy (int[] source, int startIndex, IntPtr destination, int length)
126                 {
127                         copy_to_unmanaged (source, startIndex, destination, length);
128                 }
129
130                 public static void Copy (long[] source, int startIndex, IntPtr destination, int length)
131                 {
132                         copy_to_unmanaged (source, startIndex, destination, length);
133                 }
134
135                 public static void Copy (float[] source, int startIndex, IntPtr destination, int length)
136                 {
137                         copy_to_unmanaged (source, startIndex, destination, length);
138                 }
139
140                 public static void Copy (double[] source, int startIndex, IntPtr destination, int length)
141                 {
142                         copy_to_unmanaged (source, startIndex, destination, length);
143                 }
144
145                 public static void Copy (IntPtr[] source, int startIndex, IntPtr destination, int length)
146                 {
147                         copy_to_unmanaged (source, startIndex, destination, length);
148                 }
149
150                 public static void Copy (IntPtr source, byte[] destination, int startIndex, int length)
151                 {
152                         copy_from_unmanaged (source, startIndex, destination, length);
153                 }
154
155                 public static void Copy (IntPtr source, char[] destination, int startIndex, int length)
156                 {
157                         copy_from_unmanaged (source, startIndex, destination, length);
158                 }
159
160                 public static void Copy (IntPtr source, short[] destination, int startIndex, int length)
161                 {
162                         copy_from_unmanaged (source, startIndex, destination, length);
163                 }
164
165                 public static void Copy (IntPtr source, int[] destination, int startIndex, int length)
166                 {
167                         copy_from_unmanaged (source, startIndex, destination, length);
168                 }
169
170                 public static void Copy (IntPtr source, long[] destination, int startIndex, int length)
171                 {
172                         copy_from_unmanaged (source, startIndex, destination, length);
173                 }
174
175                 public static void Copy (IntPtr source, float[] destination, int startIndex, int length)
176                 {
177                         copy_from_unmanaged (source, startIndex, destination, length);
178                 }
179
180                 public static void Copy (IntPtr source, double[] destination, int startIndex, int length)
181                 {
182                         copy_from_unmanaged (source, startIndex, destination, length);
183                 }
184
185                 public static void Copy (IntPtr source, IntPtr[] destination, int startIndex, int length)
186                 {
187                         copy_from_unmanaged (source, startIndex, destination, length);
188                 }
189
190                 public static IntPtr CreateAggregatedObject (IntPtr pOuter,
191                                                              object o)
192                 {
193                         throw new NotImplementedException ();
194                 }
195
196                 public static IntPtr CreateAggregatedObject<T> (IntPtr pOuter, T o) {
197                         return CreateAggregatedObject (pOuter, (object)o);
198                 }
199
200                 public static object CreateWrapperOfType (object o, Type t)
201                 {
202 #if FULL_AOT_RUNTIME
203                         throw new PlatformNotSupportedException ();
204 #else
205                         __ComObject co = o as __ComObject;
206                         if (co == null)
207                                 throw new ArgumentException ("o must derive from __ComObject", "o");
208                         if (t == null)
209                                 throw new ArgumentNullException ("t");
210
211                         Type[] itfs = o.GetType ().GetInterfaces ();
212                         foreach (Type itf in itfs) {
213                                 if (itf.IsImport && co.GetInterface (itf) == IntPtr.Zero)
214                                         throw new InvalidCastException ();
215                         }
216
217                         return ComInteropProxy.GetProxy (co.IUnknown, t).GetTransparentProxy ();
218 #endif
219                 }
220
221                 public static TWrapper CreateWrapperOfType<T, TWrapper> (T o) {
222                         return (TWrapper)CreateWrapperOfType ((object)o, typeof (TWrapper));
223                 }
224
225                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
226                 [ComVisible (true)]
227                 public extern static void DestroyStructure (IntPtr ptr, Type structuretype);
228
229                 public static void DestroyStructure<T> (IntPtr ptr) {
230                         DestroyStructure (ptr, typeof (T));
231                 }
232
233                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
234                 public extern static void FreeBSTR (IntPtr ptr);
235
236                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
237                 public extern static void FreeCoTaskMem (IntPtr ptr);
238
239                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
240                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
241                 public extern static void FreeHGlobal (IntPtr hglobal);
242
243                 static void ClearBSTR (IntPtr ptr)
244                 {
245                         int len = ReadInt32 (ptr, -4);
246
247                         for (int i = 0; i < len; i++)
248                                 WriteByte (ptr, i, 0);
249                 }
250                 
251                 public static void ZeroFreeBSTR (IntPtr s)
252                 {
253                         ClearBSTR (s);
254                         FreeBSTR (s);
255                 }
256
257                 static void ClearAnsi (IntPtr ptr)
258                 {
259                         for (int i = 0; ReadByte (ptr, i) != 0; i++)
260                                 WriteByte (ptr, i, 0);
261                 }
262
263                 static void ClearUnicode (IntPtr ptr)
264                 {
265                         for (int i = 0; ReadInt16 (ptr, i) != 0; i += 2)
266                                 WriteInt16 (ptr, i, 0);
267                 }
268                 
269                 public static void ZeroFreeCoTaskMemAnsi (IntPtr s)
270                 {
271                         ClearAnsi (s);
272                         FreeCoTaskMem (s);
273                 }
274
275                 public static void ZeroFreeCoTaskMemUnicode (IntPtr s)
276                 {
277                         ClearUnicode (s);
278                         FreeCoTaskMem (s);
279                 }
280
281                 public static void ZeroFreeGlobalAllocAnsi (IntPtr s)
282                 {
283                         ClearAnsi (s);
284                         FreeHGlobal (s);
285                 }
286
287                 public static void ZeroFreeGlobalAllocUnicode (IntPtr s)
288                 {
289                         ClearUnicode (s);
290                         FreeHGlobal (s);
291                 }
292
293 #if !FULL_AOT_RUNTIME
294                 public static Guid GenerateGuidForType (Type type)
295                 {
296                         return type.GUID;
297                 }
298
299                 public static string GenerateProgIdForType (Type type)
300                 {
301                         IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (type);
302
303                         foreach (var a in attrs)
304                         {
305                                 var dt = a.Constructor.DeclaringType;
306                                 string name = dt.Name;
307                                 if (name == "ProgIdAttribute")
308                                 {
309                                         var args = a.ConstructorArguments;
310                                         string text = a.ConstructorArguments[0].Value as string;
311                                         if (text == null)
312                                         {
313                                                 text = string.Empty;
314                                         }
315                                         return text;
316                                 }
317                         }
318
319                         return type.FullName;
320                 }
321
322                 [MonoTODO]
323                 public static object GetActiveObject (string progID)
324                 {
325                         throw new NotImplementedException ();
326                 }
327
328 #if !MOBILE
329                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
330                 private extern static IntPtr GetCCW (object o, Type T);
331
332                 private static IntPtr GetComInterfaceForObjectInternal (object o, Type T)
333                 {
334                         if (IsComObject (o))
335                                 return ((__ComObject)o).GetInterface (T);
336                         else
337                                 return GetCCW (o, T);
338                 }
339 #endif
340 #endif // !FULL_AOT_RUNTIME
341
342                 public static IntPtr GetComInterfaceForObject (object o, Type T)
343                 {
344 #if MOBILE
345                         throw new PlatformNotSupportedException ();
346 #else
347                         IntPtr pItf = GetComInterfaceForObjectInternal (o, T);
348                         AddRef (pItf);
349                         return pItf;
350 #endif
351                 }
352
353                 [MonoTODO]
354                 public static IntPtr GetComInterfaceForObject (object o, Type T, CustomQueryInterfaceMode mode)
355                 {
356                         throw new NotImplementedException ();
357                 }
358
359                 public static IntPtr GetComInterfaceForObject<T, TInterface> (T o) {
360                         return GetComInterfaceForObject ((object)o, typeof (T));
361                 }
362
363 #if !FULL_AOT_RUNTIME
364                 [MonoTODO]
365                 public static IntPtr GetComInterfaceForObjectInContext (object o, Type t)
366                 {
367                         throw new NotImplementedException ();
368                 }
369
370                 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
371                 public static object GetComObjectData (object obj, object key)
372                 {
373                         throw new NotSupportedException ("MSDN states user code should never need to call this method.");
374                 }
375
376 #if !MOBILE
377                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
378                 private extern static int GetComSlotForMethodInfoInternal (MemberInfo m);
379 #endif
380
381                 public static int GetComSlotForMethodInfo (MemberInfo m)
382                 {
383 #if !MOBILE
384                         if (m == null)
385                                 throw new ArgumentNullException ("m");
386                         if (!(m is MethodInfo))
387                                 throw new ArgumentException ("The MemberInfo must be an interface method.", "m");
388                         if (!m.DeclaringType.IsInterface)
389                                 throw new ArgumentException ("The MemberInfo must be an interface method.", "m");
390                         return GetComSlotForMethodInfoInternal (m);
391 #else
392                         throw new NotImplementedException ();
393 #endif
394                 }
395
396                 [MonoTODO]
397                 public static int GetEndComSlot (Type t)
398                 {
399                         throw new NotImplementedException ();
400                 }
401
402                 [MonoTODO]
403                 [ComVisible (true)]
404                 public static IntPtr GetExceptionPointers()
405                 {
406                         throw new NotImplementedException ();
407                 }
408
409                 public static IntPtr GetHINSTANCE (Module m)
410                 {
411                         if (m == null)
412                                 throw new ArgumentNullException ("m");
413
414                         return m.GetHINSTANCE ();
415                 }
416 #endif // !FULL_AOT_RUNTIME
417
418                 public static int GetExceptionCode ()
419                 {
420                         throw new PlatformNotSupportedException ();
421                 }
422
423                 public static int GetHRForException (Exception e)
424                 {
425 #if FEATURE_COMINTEROP
426                         var errorInfo = new ManagedErrorInfo(e);
427                         SetErrorInfo (0, errorInfo);
428
429                         return e._HResult;
430 #elif FULL_AOT_RUNTIME
431                         throw new PlatformNotSupportedException ();
432 #else                   
433                         return -1;
434 #endif
435                 }
436
437                 [MonoTODO]
438                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
439                 public static int GetHRForLastWin32Error()
440                 {
441 #if FULL_AOT_RUNTIME
442                         throw new PlatformNotSupportedException ();
443 #else
444                         throw new NotImplementedException ();
445 #endif
446                 }
447
448 #if !FULL_AOT_RUNTIME
449                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
450                 private extern static IntPtr GetIDispatchForObjectInternal (object o);
451
452                 public static IntPtr GetIDispatchForObject (object o)
453                 {
454                         IntPtr pUnk = GetIDispatchForObjectInternal (o);
455                         // Internal method does not AddRef
456                         AddRef (pUnk);
457                         return pUnk;
458                 }
459
460                 [MonoTODO]
461                 public static IntPtr GetIDispatchForObjectInContext (object o)
462                 {
463                         throw new NotImplementedException ();
464                 }
465
466                 [MonoTODO]
467                 public static IntPtr GetITypeInfoForType (Type t)
468                 {
469                         throw new NotImplementedException ();
470                 }
471
472                 [MonoTODO]
473                 public static IntPtr GetIUnknownForObjectInContext (object o)
474                 {
475                         throw new NotImplementedException ();
476                 }
477
478                 [MonoTODO]
479                 [Obsolete ("This method has been deprecated")]
480                 public static IntPtr GetManagedThunkForUnmanagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
481                 {
482                         throw new NotImplementedException ();
483                 }
484
485                 [MonoTODO]
486                 public static MemberInfo GetMethodInfoForComSlot (Type t, int slot, ref ComMemberType memberType)
487                 {
488                         throw new NotImplementedException ();
489                 }
490
491                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
492                 private extern static IntPtr GetIUnknownForObjectInternal (object o);
493
494 #endif // !FULL_AOT_RUNTIME
495
496                 public static IntPtr GetIUnknownForObject (object o)
497                 {
498 #if FULL_AOT_RUNTIME
499                         throw new PlatformNotSupportedException ();
500 #else
501                         IntPtr pUnk = GetIUnknownForObjectInternal (o);
502                         // Internal method does not AddRef
503                         AddRef (pUnk);
504                         return pUnk;
505 #endif
506                 }
507
508                 public static void GetNativeVariantForObject (object obj, IntPtr pDstNativeVariant)
509                 {
510 #if FULL_AOT_RUNTIME
511                         throw new PlatformNotSupportedException ();
512 #else
513                         Variant vt = new Variant();
514                         vt.SetValue(obj);
515                         Marshal.StructureToPtr(vt, pDstNativeVariant, false);
516 #endif
517                 }
518
519                 public static void GetNativeVariantForObject<T> (T obj, IntPtr pDstNativeVariant) {
520                         GetNativeVariantForObject ((object)obj, pDstNativeVariant);
521                 }
522
523 #if !MOBILE && !FULL_AOT_RUNTIME
524                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
525                 private static extern object GetObjectForCCW (IntPtr pUnk);
526 #endif
527
528                 public static object GetObjectForIUnknown (IntPtr pUnk)
529                 {
530 #if MOBILE || FULL_AOT_RUNTIME
531                         throw new PlatformNotSupportedException ();
532 #else
533                         object obj = GetObjectForCCW (pUnk);
534                         // was not a CCW
535                         if (obj == null) {
536                                 ComInteropProxy proxy = ComInteropProxy.GetProxy (pUnk, typeof (__ComObject));
537                                 obj = proxy.GetTransparentProxy ();
538                         }
539                         return obj;
540 #endif
541                 }
542
543                 public static object GetObjectForNativeVariant (IntPtr pSrcNativeVariant)
544                 {
545 #if FULL_AOT_RUNTIME
546                         throw new PlatformNotSupportedException ();
547 #else
548                         Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
549                         return vt.GetValue();
550 #endif
551                 }
552
553                 public static T GetObjectForNativeVariant<T> (IntPtr pSrcNativeVariant)
554                 {
555 #if FULL_AOT_RUNTIME
556                         throw new PlatformNotSupportedException ();
557 #else
558                         Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
559                         return (T)vt.GetValue();
560 #endif
561                 }
562
563                 public static object[] GetObjectsForNativeVariants (IntPtr aSrcNativeVariant, int cVars)
564                 {
565 #if FULL_AOT_RUNTIME
566                         throw new PlatformNotSupportedException ();
567 #else
568                         if (cVars < 0)
569                                 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
570                         object[] objects = new object[cVars];
571                         for (int i = 0; i < cVars; i++)
572                                 objects[i] = GetObjectForNativeVariant ((IntPtr)(aSrcNativeVariant.ToInt64 () +
573                                         i * SizeOf (typeof(Variant))));
574                         return objects;
575 #endif
576                 }
577
578                 public static T[] GetObjectsForNativeVariants<T> (IntPtr aSrcNativeVariant, int cVars)
579                 {
580 #if FULL_AOT_RUNTIME
581                         throw new PlatformNotSupportedException ();
582 #else
583                         if (cVars < 0)
584                                 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
585                         T[] objects = new T[cVars];
586                         for (int i = 0; i < cVars; i++)
587                                 objects[i] = GetObjectForNativeVariant<T> ((IntPtr)(aSrcNativeVariant.ToInt64 () +
588                                         i * SizeOf (typeof(Variant))));
589                         return objects;
590 #endif
591                 }
592
593                 [MonoTODO]
594                 public static int GetStartComSlot (Type t)
595                 {
596 #if FULL_AOT_RUNTIME
597                         throw new PlatformNotSupportedException ();
598 #else
599                         throw new NotImplementedException ();
600 #endif
601                 }
602
603 #if !FULL_AOT_RUNTIME
604                 [MonoTODO]
605                 [Obsolete ("This method has been deprecated")]
606                 public static Thread GetThreadFromFiberCookie (int cookie)
607                 {
608                         throw new NotImplementedException ();
609                 }
610
611                 public static object GetTypedObjectForIUnknown (IntPtr pUnk, Type t)
612                 {
613                         ComInteropProxy proxy = new ComInteropProxy (pUnk, t);
614                         __ComObject co = (__ComObject)proxy.GetTransparentProxy ();
615                         foreach (Type itf in t.GetInterfaces ()) {
616                                 if ((itf.Attributes & TypeAttributes.Import) == TypeAttributes.Import) {
617                                         if (co.GetInterface (itf) == IntPtr.Zero)
618                                                 return null;
619                                 }
620                         }
621                         return co;
622                 }
623
624                 [MonoTODO]
625                 public static Type GetTypeForITypeInfo (IntPtr piTypeInfo)
626                 {
627                         throw new NotImplementedException ();
628                 }
629
630                 [Obsolete]
631                 [MonoTODO]
632                 public static string GetTypeInfoName (UCOMITypeInfo pTI)
633                 {
634                         throw new NotImplementedException ();
635                 }
636
637                 [Obsolete]
638                 [MonoTODO]
639                 public static Guid GetTypeLibGuid (UCOMITypeLib pTLB)
640                 {
641                         throw new NotImplementedException ();
642                 }
643
644                 [MonoTODO]
645                 public static Guid GetTypeLibGuid (ITypeLib typelib)
646                 {
647                         throw new NotImplementedException ();
648                 }
649
650                 [MonoTODO]
651                 public static Guid GetTypeLibGuidForAssembly (Assembly asm)
652                 {
653                         throw new NotImplementedException ();
654                 }
655
656                 [Obsolete]
657                 [MonoTODO]
658                 public static int GetTypeLibLcid (UCOMITypeLib pTLB)
659                 {
660                         throw new NotImplementedException ();
661                 }
662
663                 [MonoTODO]
664                 public static int GetTypeLibLcid (ITypeLib typelib)
665                 {
666                         throw new NotImplementedException ();
667                 }
668
669                 [Obsolete]
670                 [MonoTODO]
671                 public static string GetTypeLibName (UCOMITypeLib pTLB)
672                 {
673                         throw new NotImplementedException ();
674                 }
675
676                 [MonoTODO]
677                 public static string GetTypeLibName (ITypeLib typelib)
678                 {
679                         throw new NotImplementedException ();
680                 }
681
682                 [MonoTODO]
683                 public static void GetTypeLibVersionForAssembly (Assembly inputAssembly, out int majorVersion, out int minorVersion)
684                 {
685                         throw new NotImplementedException ();
686                 }
687
688                 [MonoTODO]
689                 [Obsolete ("This method has been deprecated")]
690                 public static IntPtr GetUnmanagedThunkForManagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
691                 {
692                         throw new NotImplementedException ();
693                 }
694
695                 [MonoTODO]
696                 public static bool IsTypeVisibleFromCom (Type t)
697                 {
698                         throw new NotImplementedException ();
699                 }
700
701                 [MonoTODO]
702                 public static int NumParamBytes (MethodInfo m)
703                 {
704                         throw new NotImplementedException ();
705                 }
706 #endif // !FULL_AOT_RUNTIME
707
708                 public static Type GetTypeFromCLSID (Guid clsid)
709                 {
710                         throw new PlatformNotSupportedException ();
711                 }
712
713                 public static string GetTypeInfoName (ITypeInfo typeInfo)
714                 {
715                         throw new PlatformNotSupportedException ();
716                 }
717
718                 public static object GetUniqueObjectForIUnknown (IntPtr unknown)
719                 {
720                         throw new PlatformNotSupportedException ();
721                 }
722
723 #if !MOBILE
724                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
725                 public extern static bool IsComObject (object o);
726 #else
727                 public static bool IsComObject (object o)
728                 {
729                         throw new PlatformNotSupportedException ();
730                 }
731 #endif
732
733                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
734                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
735                 public static extern int GetLastWin32Error();
736
737                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
738                 public extern static IntPtr OffsetOf (Type t, string fieldName);
739
740                 public static IntPtr OffsetOf<T> (string fieldName) {
741                         return OffsetOf (typeof (T), fieldName);
742                 }
743
744                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
745                 public extern static void Prelink (MethodInfo m);
746
747                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
748                 public extern static void PrelinkAll (Type c);
749
750                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
751                 public extern static string PtrToStringAnsi (IntPtr ptr);
752                 
753                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
754                 public extern static string PtrToStringAnsi (IntPtr ptr, int len);
755
756                 public static string PtrToStringAuto (IntPtr ptr)
757                 {
758                         return SystemDefaultCharSize == 2
759                                 ? PtrToStringUni (ptr) : PtrToStringAnsi (ptr);
760                 }
761                 
762                 public static string PtrToStringAuto (IntPtr ptr, int len)
763                 {
764                         return SystemDefaultCharSize == 2
765                                 ? PtrToStringUni (ptr, len) : PtrToStringAnsi (ptr, len);
766                 }
767
768                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
769                 public extern static string PtrToStringUni (IntPtr ptr);
770
771                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
772                 public extern static string PtrToStringUni (IntPtr ptr, int len);
773
774 #if !MOBILE
775                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
776                 public extern static string PtrToStringBSTR (IntPtr ptr);
777 #else
778                 public static string PtrToStringBSTR (IntPtr ptr)
779                 {
780                         throw new NotImplementedException ();
781                 }
782 #endif
783                 
784                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
785                 [ComVisible (true)]
786                 public extern static void PtrToStructure (IntPtr ptr, object structure);
787
788                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
789                 [ComVisible (true)]
790                 public extern static object PtrToStructure (IntPtr ptr, Type structureType);
791
792                 public static void PtrToStructure<T> (IntPtr ptr, T structure) {
793                         PtrToStructure (ptr, (object)structure);
794                 }
795
796                 public static T PtrToStructure<T> (IntPtr ptr) {
797                         return (T) PtrToStructure (ptr, typeof (T));
798                 }
799
800 #if !MOBILE
801                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
802                 private extern static int QueryInterfaceInternal (IntPtr pUnk, ref Guid iid, out IntPtr ppv);
803 #endif
804
805                 public static int QueryInterface (IntPtr pUnk, ref Guid iid, out IntPtr ppv)
806                 {
807 #if !MOBILE
808                         if (pUnk == IntPtr.Zero)
809                                 throw new ArgumentException ("Value cannot be null.", "pUnk");
810                         return QueryInterfaceInternal (pUnk, ref iid, out ppv);
811 #else
812                         throw new NotImplementedException ();
813 #endif
814                 }
815
816                 public static byte ReadByte (IntPtr ptr)
817                 {
818                         unsafe {
819                                 return *(byte*)ptr;
820                         }
821                 }
822
823                 public static byte ReadByte (IntPtr ptr, int ofs) {
824                         unsafe {
825                                 return *((byte*)ptr + ofs);
826                         }
827                 }
828
829                 [MonoTODO]
830                 [SuppressUnmanagedCodeSecurity]
831                 public static byte ReadByte ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
832                 {
833                         throw new NotImplementedException ();
834                 }
835
836                 public unsafe static short ReadInt16 (IntPtr ptr)
837                 {
838                         byte *addr = (byte *) ptr;
839                         
840                         // The mono JIT can't inline this due to the hight number of calls
841                         // return ReadInt16 (ptr, 0);
842                         
843                         if (((uint)addr & 1) == 0) 
844                                 return *(short*)addr;
845
846                         short s;
847                         Buffer.Memcpy ((byte*)&s, (byte*)ptr, 2);
848                         return s;
849                 }
850
851                 public unsafe static short ReadInt16 (IntPtr ptr, int ofs)
852                 {
853                         byte *addr = ((byte *) ptr) + ofs;
854
855                         if (((uint) addr & 1) == 0)
856                                 return *(short*)addr;
857
858                         short s;
859                         Buffer.Memcpy ((byte*)&s, addr, 2);
860                         return s;
861                 }
862
863                 [MonoTODO]
864                 [SuppressUnmanagedCodeSecurity]
865                 public static short ReadInt16 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
866                 {
867                         throw new NotImplementedException ();
868                 }
869
870                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
871                 public unsafe static int ReadInt32 (IntPtr ptr)
872                 {
873                         byte *addr = (byte *) ptr;
874                         
875                         if (((uint)addr & 3) == 0) 
876                                 return *(int*)addr;
877
878                         int s;
879                         Buffer.Memcpy ((byte*)&s, addr, 4);
880                         return s;
881                 }
882
883                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
884                 public unsafe static int ReadInt32 (IntPtr ptr, int ofs)
885                 {
886                         byte *addr = ((byte *) ptr) + ofs;
887                         
888                         if ((((int) addr) & 3) == 0)
889                                 return *(int*)addr;
890                         else {
891                                 int s;
892                                 Buffer.Memcpy ((byte*)&s, addr, 4);
893                                 return s;
894                         }
895                 }
896
897                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
898                 [MonoTODO]
899                 [SuppressUnmanagedCodeSecurity]
900                 public static int ReadInt32 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
901                 {
902                         throw new NotImplementedException ();
903                 }
904
905                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
906                 public unsafe static long ReadInt64 (IntPtr ptr)
907                 {
908                         byte *addr = (byte *) ptr;
909                                 
910                         // The real alignment might be 4 on some platforms, but this is just an optimization,
911                         // so it doesn't matter.
912                         if (((uint) addr & 7) == 0)
913                                 return *(long*)ptr;
914
915                         long s;
916                         Buffer.Memcpy ((byte*)&s, addr, 8);
917                         return s;
918                 }
919
920                 public unsafe static long ReadInt64 (IntPtr ptr, int ofs)
921                 {
922                         byte *addr = ((byte *) ptr) + ofs;
923
924                         if (((uint) addr & 7) == 0)
925                                 return *(long*)addr;
926                         
927                         long s;
928                         Buffer.Memcpy ((byte*)&s, addr, 8);
929                         return s;
930                 }
931
932                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
933                 [MonoTODO]
934                 [SuppressUnmanagedCodeSecurity]
935                 public static long ReadInt64 ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
936                 {
937                         throw new NotImplementedException ();
938                 }
939
940                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
941                 public static IntPtr ReadIntPtr (IntPtr ptr)
942                 {
943                         if (IntPtr.Size == 4)
944                                 return (IntPtr)ReadInt32 (ptr);
945                         else
946                                 return (IntPtr)ReadInt64 (ptr);
947                 }
948                 
949                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
950                 public static IntPtr ReadIntPtr (IntPtr ptr, int ofs)
951                 {
952                         if (IntPtr.Size == 4)
953                                 return (IntPtr)ReadInt32 (ptr, ofs);
954                         else
955                                 return (IntPtr)ReadInt64 (ptr, ofs);
956                 }
957
958                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
959                 [MonoTODO]
960                 public static IntPtr ReadIntPtr ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
961                 {
962                         throw new NotImplementedException ();
963                 }
964
965                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
966                 public extern static IntPtr ReAllocCoTaskMem (IntPtr pv, int cb);
967
968                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
969                 public extern static IntPtr ReAllocHGlobal (IntPtr pv, IntPtr cb);
970
971 #if !MOBILE
972                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
973                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
974                 private extern static int ReleaseInternal (IntPtr pUnk);
975 #endif
976
977                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
978                 public static int Release (IntPtr pUnk)
979                 {
980 #if !MOBILE
981                         if (pUnk == IntPtr.Zero)
982                                 throw new ArgumentException ("Value cannot be null.", "pUnk");
983
984                         return ReleaseInternal (pUnk);
985 #else
986                         throw new NotImplementedException ();
987 #endif
988                 }
989
990 #if !FULL_AOT_RUNTIME
991                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
992                 private extern static int ReleaseComObjectInternal (object co);
993 #endif
994
995                 public static int ReleaseComObject (object o)
996                 {
997 #if FULL_AOT_RUNTIME
998                         throw new PlatformNotSupportedException ();
999 #else
1000                         if (o == null)
1001                                 throw new ArgumentException ("Value cannot be null.", "o");
1002                         if (!IsComObject (o))
1003                                 throw new ArgumentException ("Value must be a Com object.", "o");
1004                         return ReleaseComObjectInternal (o);
1005 #endif
1006                 }
1007
1008 #if !FULL_AOT_RUNTIME
1009                 [Obsolete]
1010                 [MonoTODO]
1011                 public static void ReleaseThreadCache()
1012                 {
1013                         throw new NotImplementedException ();
1014                 }
1015
1016                 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
1017                 public static bool SetComObjectData (object obj, object key, object data)
1018                 {
1019                         throw new NotSupportedException ("MSDN states user code should never need to call this method.");
1020                 }
1021 #endif
1022
1023                 [ComVisible (true)]
1024                 public static int SizeOf (object structure)
1025                 {
1026                         return SizeOf (structure.GetType ());
1027                 }
1028
1029                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1030                 public extern static int SizeOf (Type t);
1031
1032                 public static int SizeOf<T> () {
1033                         return SizeOf (typeof (T));
1034                 }
1035
1036                 public static int SizeOf<T> (T structure) {
1037                         return SizeOf (structure.GetType ());
1038                 }
1039
1040                 internal static uint SizeOfType (Type type)
1041                 {
1042                         return (uint) SizeOf (type);
1043                 }
1044
1045                 internal static uint AlignedSizeOf<T> () where T : struct
1046                 {
1047                         uint size = SizeOfType (typeof (T));
1048                         if (size == 1 || size == 2)
1049                                 return size;
1050                         if (IntPtr.Size == 8 && size == 4)
1051                                 return size;
1052                         return (size + 3) & (~((uint)3));
1053                 }
1054
1055                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1056                 public extern static IntPtr StringToBSTR (string s);
1057
1058                 //
1059                 // I believe this is wrong, because in Mono and in P/Invoke
1060                 // we treat "Ansi" conversions as UTF-8 conversions, while
1061                 // this one does not do this
1062                 //
1063                 public static IntPtr StringToCoTaskMemAnsi (string s)
1064                 {
1065                         int length = s.Length + 1;
1066                         IntPtr ctm = AllocCoTaskMem (length);
1067
1068                         byte[] asBytes = new byte[length];
1069                         for (int i = 0; i < s.Length; i++)
1070                                 asBytes[i] = (byte)s[i];
1071                         asBytes[s.Length] = 0;
1072
1073                         copy_to_unmanaged (asBytes, 0, ctm, length);
1074                         return ctm;
1075                 }
1076
1077                 public static IntPtr StringToCoTaskMemAuto (string s)
1078                 {
1079                         return SystemDefaultCharSize == 2
1080                                 ? StringToCoTaskMemUni (s) : StringToCoTaskMemAnsi (s);
1081                 }
1082
1083                 public static IntPtr StringToCoTaskMemUni (string s)
1084                 {
1085                         int length = s.Length + 1;
1086                         IntPtr ctm = AllocCoTaskMem (length * 2);
1087                         
1088                         char[] asChars = new char[length];
1089                         s.CopyTo (0, asChars, 0, s.Length);
1090                         asChars[s.Length] = '\0';
1091
1092                         copy_to_unmanaged (asChars, 0, ctm, length);
1093                         return ctm;
1094                 }
1095
1096                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1097                 public extern static IntPtr StringToHGlobalAnsi (string s);
1098
1099                 public static IntPtr StringToHGlobalAuto (string s)
1100                 {
1101                         return SystemDefaultCharSize == 2
1102                                 ? StringToHGlobalUni (s) : StringToHGlobalAnsi (s);
1103                 }
1104
1105                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1106                 public extern static IntPtr StringToHGlobalUni (string s);
1107
1108                 public static IntPtr SecureStringToBSTR (SecureString s)
1109                 {
1110                         if (s == null)
1111                                 throw new ArgumentNullException ("s");
1112
1113                         byte[] buffer = s.GetBuffer ();
1114                         int len = s.Length;
1115                         
1116                         // SecureString doesn't take endian-ness into account. 
1117                         // Therefore swap bytes here before we send it to c-side if little-endian.
1118                         if (BitConverter.IsLittleEndian) {
1119                                 for (int i = 0; i < buffer.Length; i += 2) {
1120                                         byte b = buffer[i];
1121                                         buffer[i] = buffer[i + 1];
1122                                         buffer[i + 1] = b;
1123                                 }
1124                         }
1125                         return BufferToBSTR (buffer, len);
1126         }
1127
1128                 public static IntPtr SecureStringToCoTaskMemAnsi (SecureString s)
1129                 {
1130                         if (s == null)
1131                                 throw new ArgumentNullException ("s");
1132                         int len = s.Length;
1133                         IntPtr ctm = AllocCoTaskMem (len + 1);
1134                         byte [] copy = new byte [len+1];
1135
1136                         try {
1137                                 byte [] buffer = s.GetBuffer ();
1138                                 int i = 0, j = 0;
1139                                 for (; i < len; i++, j += 2){
1140                                         copy [i] = buffer [j+1];
1141                                         buffer [j] = 0;
1142                                         buffer [j+1] = 0;
1143                                 }
1144                                 copy [i] = 0;
1145                                 copy_to_unmanaged (copy, 0, ctm, len+1);
1146                         } finally {
1147                                 // Ensure that we clear the buffer.
1148                                 for (int i = len; i > 0; ){
1149                                         i--;
1150                                         copy [i] = 0;
1151                                 }
1152                         }
1153                         return ctm;
1154                 }
1155
1156                 public static IntPtr SecureStringToCoTaskMemUnicode (SecureString s)
1157                 {
1158                         if (s == null)
1159                                 throw new ArgumentNullException ("s");
1160                         int len = s.Length;
1161                         IntPtr ctm = AllocCoTaskMem (len * 2 + 2);
1162                         byte [] buffer = null;
1163                         try {
1164                                 buffer = s.GetBuffer ();
1165                                 for (int i = 0; i < len; i++)
1166                                         WriteInt16 (ctm, i * 2, (short) ((buffer [(i*2)] << 8) | (buffer [i*2+1])));
1167                                 WriteInt16 (ctm, buffer.Length, 0);
1168                         } finally {
1169                                 if (buffer != null)
1170                                         for (int i = buffer.Length; i > 0; ){
1171                                                 i--;
1172                                                 buffer [i] = 0;
1173                                         }
1174                         }
1175                         return ctm;
1176                 }
1177
1178                 public static IntPtr SecureStringToGlobalAllocAnsi (SecureString s)
1179                 {
1180                         if (s == null)
1181                                 throw new ArgumentNullException ("s");
1182                         return SecureStringToCoTaskMemAnsi (s);
1183                 }
1184
1185                 public static IntPtr SecureStringToGlobalAllocUnicode (SecureString s)
1186                 {
1187                         if (s == null)
1188                                 throw new ArgumentNullException ("s");
1189                         return SecureStringToCoTaskMemUnicode (s);
1190                 }
1191
1192                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
1193                 [ComVisible (true)]
1194                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1195                 public extern static void StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld);
1196
1197                 public static void StructureToPtr<T> (T structure, IntPtr ptr, bool fDeleteOld) {
1198                         StructureToPtr ((object)structure, ptr, fDeleteOld);
1199                 }
1200
1201                 public static void ThrowExceptionForHR (int errorCode) {
1202                         Exception ex = GetExceptionForHR (errorCode);
1203                         if (ex != null)
1204                                 throw ex;
1205                 }
1206
1207                 public static void ThrowExceptionForHR (int errorCode, IntPtr errorInfo) {
1208                         Exception ex = GetExceptionForHR (errorCode, errorInfo);
1209                         if (ex != null)
1210                                 throw ex;
1211                 }
1212
1213
1214                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1215                 public extern static IntPtr BufferToBSTR (Array ptr, int slen);
1216
1217                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1218                 public extern static IntPtr UnsafeAddrOfPinnedArrayElement (Array arr, int index);
1219
1220                 public static IntPtr UnsafeAddrOfPinnedArrayElement<T> (T[] arr, int index) {
1221                         return UnsafeAddrOfPinnedArrayElement ((Array)arr, index);
1222                 }
1223
1224                 public static void WriteByte (IntPtr ptr, byte val)
1225                 {
1226                         unsafe {
1227                                 *(byte*)ptr = val;
1228                         }
1229                 }
1230
1231                 public static void WriteByte (IntPtr ptr, int ofs, byte val) {
1232                         unsafe {
1233                                 *(byte*)(IntPtr.Add (ptr, ofs)) = val;
1234                         }
1235                 }
1236
1237                 [MonoTODO]
1238                 [SuppressUnmanagedCodeSecurity]
1239                 public static void WriteByte ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, byte val)
1240                 {
1241                         throw new NotImplementedException ();
1242                 }
1243
1244                 public static unsafe void WriteInt16 (IntPtr ptr, short val)
1245                 {
1246                         byte *addr = (byte *) ptr;
1247                         
1248                         if (((uint)addr & 1) == 0)
1249                                 *(short*)addr = val;
1250                         else
1251                                 Buffer.Memcpy (addr, (byte*)&val, 2);
1252                 }
1253
1254                 public static unsafe void WriteInt16 (IntPtr ptr, int ofs, short val)
1255                 {
1256                         byte *addr = ((byte *) ptr) + ofs;
1257
1258                         if (((uint)addr & 1) == 0)
1259                                 *(short*)addr = val;
1260                         else {
1261                                 Buffer.Memcpy (addr, (byte*)&val, 2);
1262                         }
1263                 }
1264
1265                 [MonoTODO]
1266                 [SuppressUnmanagedCodeSecurity]
1267                 public static void WriteInt16 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, short val)
1268                 {
1269                         throw new NotImplementedException ();
1270                 }
1271
1272                 public static void WriteInt16 (IntPtr ptr, char val)
1273                 {
1274                         WriteInt16 (ptr, 0, (short)val);
1275                 }
1276
1277                 public static void WriteInt16 (IntPtr ptr, int ofs, char val)
1278                 {
1279                         WriteInt16 (ptr, ofs, (short)val);
1280                 }
1281
1282                 [MonoTODO]
1283                 public static void WriteInt16([In, Out] object ptr, int ofs, char val)
1284                 {
1285                         throw new NotImplementedException ();
1286                 }
1287
1288                 public static unsafe void WriteInt32 (IntPtr ptr, int val)
1289                 {
1290                         byte *addr = (byte *) ptr;
1291                         
1292                         if (((uint)addr & 3) == 0) 
1293                                 *(int*)addr = val;
1294                         else {
1295                                 Buffer.Memcpy (addr, (byte*)&val, 4);
1296                         }
1297                 }
1298
1299                 public unsafe static void WriteInt32 (IntPtr ptr, int ofs, int val)
1300                 {
1301                         byte *addr = ((byte *) ptr) + ofs;
1302
1303                         if (((uint)addr & 3) == 0) 
1304                                 *(int*)addr = val;
1305                         else {
1306                                 Buffer.Memcpy (addr, (byte*)&val, 4);
1307                         }
1308                 }
1309
1310                 [MonoTODO]
1311                 [SuppressUnmanagedCodeSecurity]
1312                 public static void WriteInt32([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, int val)
1313                 {
1314                         throw new NotImplementedException ();
1315                 }
1316
1317                 public static unsafe void WriteInt64 (IntPtr ptr, long val)
1318                 {
1319                         byte *addr = (byte *) ptr;
1320                         
1321                         // The real alignment might be 4 on some platforms, but this is just an optimization,
1322                         // so it doesn't matter.
1323                         if (((uint)addr & 7) == 0) 
1324                                 *(long*)addr = val;
1325                         else 
1326                                 Buffer.Memcpy (addr, (byte*)&val, 8);
1327                 }
1328
1329                 public static unsafe void WriteInt64 (IntPtr ptr, int ofs, long val)
1330                 {
1331                         byte *addr = ((byte *) ptr) + ofs;
1332
1333                         // The real alignment might be 4 on some platforms, but this is just an optimization,
1334                         // so it doesn't matter.
1335                         if (((uint)addr & 7) == 0) 
1336                                 *(long*)addr = val;
1337                         else 
1338                                 Buffer.Memcpy (addr, (byte*)&val, 8);
1339                 }
1340
1341                 [MonoTODO]
1342                 [SuppressUnmanagedCodeSecurity]
1343                 public static void WriteInt64 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, long val)
1344                 {
1345                         throw new NotImplementedException ();
1346                 }
1347
1348                 public static void WriteIntPtr (IntPtr ptr, IntPtr val)
1349                 {
1350                         if (IntPtr.Size == 4)
1351                                 WriteInt32 (ptr, (int)val);
1352                         else
1353                                 WriteInt64 (ptr, (long)val);
1354                 }
1355
1356                 public static void WriteIntPtr (IntPtr ptr, int ofs, IntPtr val)
1357                 {
1358                         if (IntPtr.Size == 4)
1359                                 WriteInt32 (ptr, ofs, (int)val);
1360                         else
1361                                 WriteInt64 (ptr, ofs, (long)val);
1362                 }
1363
1364                 [MonoTODO]
1365                 public static void WriteIntPtr([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, IntPtr val)
1366                 {
1367                         throw new NotImplementedException ();
1368                 }
1369
1370                 private static Exception ConvertHrToException (int errorCode)
1371                 {
1372                         const int MSEE_E_APPDOMAINUNLOADED = unchecked ((int)0x80131014L);
1373                         const int COR_E_APPLICATION = unchecked ((int)0x80131600L);
1374                         const int E_INVALIDARG = unchecked ((int)0x80070057);
1375                         const int COR_E_ARGUMENTOUTOFRANGE = unchecked ((int)0x80131502L);
1376                         const int COR_E_ARITHMETIC = unchecked ((int)0x80070216);
1377                         const int COR_E_ARRAYTYPEMISMATCH = unchecked ((int)0x80131503L);
1378                         const int COR_E_BADIMAGEFORMAT = unchecked ((int)0x8007000BL);
1379                         const int ERROR_BAD_FORMAT = unchecked ((int)0x0B);
1380                         //const int COR_E_COMEMULATE_ERROR = unchecked ((int)?);
1381                         const int COR_E_CONTEXTMARSHAL = unchecked ((int)0x80131504L);
1382                         //const int COR_E_CORE = unchecked ((int)?);
1383                         const int NTE_FAIL = unchecked ((int)0x80090020L);
1384                         const int COR_E_DIRECTORYNOTFOUND = unchecked ((int)0x80070003L);
1385                         const int ERROR_PATH_NOT_FOUND = unchecked ((int)0x03);
1386                         const int COR_E_DIVIDEBYZERO = unchecked ((int)0x80020012L);
1387                         const int COR_E_DUPLICATEWAITOBJECT = unchecked ((int)0x80131529L);
1388                         const int COR_E_ENDOFSTREAM = unchecked ((int)0x80070026L);
1389                         const int COR_E_TYPELOAD = unchecked ((int)0x80131522L);
1390                         const int COR_E_EXCEPTION = unchecked ((int)0x80131500L);
1391                         const int COR_E_EXECUTIONENGINE = unchecked ((int)0x80131506L);
1392                         const int COR_E_FIELDACCESS = unchecked ((int)0x80131507L);
1393                         const int COR_E_FILENOTFOUND = unchecked ((int)0x80070002L);
1394                         const int ERROR_FILE_NOT_FOUND = unchecked ((int)0x02);
1395                         const int COR_E_FORMAT = unchecked ((int)0x80131537L);
1396                         const int COR_E_INDEXOUTOFRANGE = unchecked ((int)0x80131508L);
1397                         const int COR_E_INVALIDCAST = unchecked ((int)0x80004002L);
1398                         const int COR_E_INVALIDCOMOBJECT = unchecked ((int)0x80131527L);
1399                         const int COR_E_INVALIDFILTERCRITERIA = unchecked ((int)0x80131601L);
1400                         const int COR_E_INVALIDOLEVARIANTTYPE = unchecked ((int)0x80131531L);
1401                         const int COR_E_INVALIDOPERATION = unchecked ((int)0x80131509L);
1402                         const int COR_E_IO = unchecked ((int)0x80131620L);
1403                         const int COR_E_MEMBERACCESS = unchecked ((int)0x8013151AL);
1404                         const int COR_E_METHODACCESS = unchecked ((int)0x80131510L);
1405                         const int COR_E_MISSINGFIELD = unchecked ((int)0x80131511L);
1406                         const int COR_E_MISSINGMANIFESTRESOURCE = unchecked ((int)0x80131532L);
1407                         const int COR_E_MISSINGMEMBER = unchecked ((int)0x80131512L);
1408                         const int COR_E_MISSINGMETHOD = unchecked ((int)0x80131513L);
1409                         const int COR_E_MULTICASTNOTSUPPORTED = unchecked ((int)0x80131514L);
1410                         const int COR_E_NOTFINITENUMBER = unchecked ((int)0x80131528L);
1411                         const int E_NOTIMPL = unchecked ((int)0x80004001L);
1412                         const int COR_E_NOTSUPPORTED = unchecked ((int)0x80131515L);
1413                         const int COR_E_NULLREFERENCE = unchecked ((int)0x80004003L);
1414                         const int E_OUTOFMEMORY = unchecked ((int)0x8007000EL);
1415                         const int COR_E_OVERFLOW = unchecked ((int)0x80131516L);
1416                         const int COR_E_PATHTOOLONG = unchecked ((int)0x800700CEL);
1417                         const int ERROR_FILENAME_EXCED_RANGE = unchecked ((int)0xCE);
1418                         const int COR_E_RANK = unchecked ((int)0x80131517L);
1419                         const int COR_E_REFLECTIONTYPELOAD = unchecked ((int)0x80131602L);
1420                         const int COR_E_REMOTING = unchecked ((int)0x8013150BL);
1421                         const int COR_E_SAFEARRAYTYPEMISMATCH = unchecked ((int)0x80131533L);
1422                         const int COR_E_SECURITY = unchecked ((int)0x8013150AL);
1423                         const int COR_E_SERIALIZATION = unchecked ((int)0x8013150CL);
1424                         const int COR_E_STACKOVERFLOW = unchecked ((int)0x800703E9L);
1425                         const int ERROR_STACK_OVERFLOW = unchecked ((int)0x03E9);
1426                         const int COR_E_SYNCHRONIZATIONLOCK = unchecked ((int)0x80131518L);
1427                         const int COR_E_SYSTEM = unchecked ((int)0x80131501L);
1428                         const int COR_E_TARGET = unchecked ((int)0x80131603L);
1429                         const int COR_E_TARGETINVOCATION = unchecked ((int)0x80131604L);
1430                         const int COR_E_TARGETPARAMCOUNT = unchecked ((int)0x8002000EL);
1431                         const int COR_E_THREADABORTED = unchecked ((int)0x80131530L);
1432                         const int COR_E_THREADINTERRUPTED = unchecked ((int)0x80131519L);
1433                         const int COR_E_THREADSTATE = unchecked ((int)0x80131520L);
1434                         const int COR_E_THREADSTOP = unchecked ((int)0x80131521L);
1435                         const int COR_E_TYPEINITIALIZATION = unchecked ((int)0x80131534L);
1436                         const int COR_E_VERIFICATION = unchecked ((int)0x8013150DL);
1437                         //const int COR_E_WEAKREFERENCE = unchecked ((int)?);
1438                         //const int COR_E_VTABLECALLSNOTSUPPORTED = unchecked ((int));
1439
1440                         switch (errorCode) {
1441                                 case MSEE_E_APPDOMAINUNLOADED:
1442                                         return new AppDomainUnloadedException ();
1443                                 case COR_E_APPLICATION:
1444                                         return new ApplicationException ();
1445                                 case E_INVALIDARG:
1446                                         return new ArgumentException ();
1447                                 case COR_E_ARGUMENTOUTOFRANGE:
1448                                         return new ArgumentOutOfRangeException ();
1449                                 case COR_E_ARITHMETIC:
1450                                         return new ArithmeticException ();
1451                                 case COR_E_ARRAYTYPEMISMATCH:
1452                                         return new ArrayTypeMismatchException ();
1453                                 case COR_E_BADIMAGEFORMAT:
1454                                 case ERROR_BAD_FORMAT:
1455                                         return new BadImageFormatException ();
1456 //                              case COR_E_COMEMULATE_ERROR:
1457 //                                      return new COMEmulateException ();
1458                                 case COR_E_CONTEXTMARSHAL:
1459                                         return new ContextMarshalException ();
1460 //                              case COR_E_CORE:
1461 //                                      return new CoreException ();
1462                                 case NTE_FAIL:
1463                                         return new System.Security.Cryptography.CryptographicException ();
1464                                 case COR_E_DIRECTORYNOTFOUND:
1465                                 case ERROR_PATH_NOT_FOUND:
1466                                         return new System.IO.DirectoryNotFoundException ();
1467                                 case COR_E_DIVIDEBYZERO:
1468                                         return new DivideByZeroException ();
1469                                 case COR_E_DUPLICATEWAITOBJECT:
1470                                         return new DuplicateWaitObjectException ();
1471                                 case COR_E_ENDOFSTREAM:
1472                                         return new System.IO.EndOfStreamException ();
1473                                 case COR_E_EXCEPTION:
1474                                         return new Exception ();
1475                                 case COR_E_EXECUTIONENGINE:
1476                                         return new ExecutionEngineException ();
1477                                 case COR_E_FIELDACCESS:
1478                                         return new FieldAccessException ();
1479                                 case COR_E_FILENOTFOUND:
1480                                 case ERROR_FILE_NOT_FOUND:
1481                                         return new System.IO.FileNotFoundException ();
1482                                 case COR_E_FORMAT:
1483                                         return new FormatException ();
1484                                 case COR_E_INDEXOUTOFRANGE:
1485                                         return new IndexOutOfRangeException ();
1486                                 case COR_E_INVALIDCAST:
1487                                 // E_NOINTERFACE has same value as COR_E_INVALIDCAST
1488                                         return new InvalidCastException ();
1489                                 case COR_E_INVALIDCOMOBJECT:
1490                                         return new InvalidComObjectException ();
1491                                 case COR_E_INVALIDFILTERCRITERIA:
1492                                         return new InvalidFilterCriteriaException ();
1493                                 case COR_E_INVALIDOLEVARIANTTYPE:
1494                                         return new InvalidOleVariantTypeException ();
1495                                 case COR_E_INVALIDOPERATION:
1496                                         return new InvalidOperationException ();
1497                                 case COR_E_IO:
1498                                         return new System.IO.IOException ();
1499                                 case COR_E_MEMBERACCESS:
1500                                         return new MemberAccessException ();
1501                                 case COR_E_METHODACCESS:
1502                                         return new MethodAccessException ();
1503                                 case COR_E_MISSINGFIELD:
1504                                         return new MissingFieldException ();
1505                                 case COR_E_MISSINGMANIFESTRESOURCE:
1506                                         return new System.Resources.MissingManifestResourceException ();
1507                                 case COR_E_MISSINGMEMBER:
1508                                         return new MissingMemberException ();
1509                                 case COR_E_MISSINGMETHOD:
1510                                         return new MissingMethodException ();
1511                                 case COR_E_MULTICASTNOTSUPPORTED:
1512                                         return new MulticastNotSupportedException ();
1513                                 case COR_E_NOTFINITENUMBER:
1514                                         return new NotFiniteNumberException ();
1515                                 case E_NOTIMPL:
1516                                         return new NotImplementedException ();
1517                                 case COR_E_NOTSUPPORTED:
1518                                         return new NotSupportedException ();
1519                                 case COR_E_NULLREFERENCE:
1520                                 // E_POINTER has the same value as COR_E_NULLREFERENCE
1521                                         return new NullReferenceException ();
1522                                 case E_OUTOFMEMORY:
1523                                 // COR_E_OUTOFMEMORY has the same value as E_OUTOFMEMORY
1524                                         return new OutOfMemoryException ();
1525                                 case COR_E_OVERFLOW:
1526                                         return new OverflowException ();
1527                                 case COR_E_PATHTOOLONG:
1528                                 case ERROR_FILENAME_EXCED_RANGE:
1529                                         return new System.IO.PathTooLongException ();
1530                                 case COR_E_RANK:
1531                                         return new RankException ();
1532                                 case COR_E_REFLECTIONTYPELOAD:
1533                                         return new System.Reflection.ReflectionTypeLoadException (new Type[] { }, new Exception[] { });
1534                                 case COR_E_REMOTING:
1535                                         return new System.Runtime.Remoting.RemotingException ();
1536                                 case COR_E_SAFEARRAYTYPEMISMATCH:
1537                                         return new SafeArrayTypeMismatchException ();
1538                                 case COR_E_SECURITY:
1539                                         return new SecurityException ();
1540                                 case COR_E_SERIALIZATION:
1541                                         return new System.Runtime.Serialization.SerializationException ();
1542                                 case COR_E_STACKOVERFLOW:
1543                                 case ERROR_STACK_OVERFLOW:
1544                                         return new StackOverflowException ();
1545                                 case COR_E_SYNCHRONIZATIONLOCK:
1546                                         return new SynchronizationLockException ();
1547                                 case COR_E_SYSTEM:
1548                                         return new SystemException ();
1549                                 case COR_E_TARGET:
1550                                         return new TargetException ();
1551                                 case COR_E_TARGETINVOCATION:
1552                                         return new System.Reflection.TargetInvocationException (null);
1553                                 case COR_E_TARGETPARAMCOUNT:
1554                                         return new TargetParameterCountException ();
1555 //                              case COR_E_THREADABORTED:
1556 //                                      ThreadAbortException c'tor is inaccessible
1557 //                                      return new System.Threading.ThreadAbortException ();
1558                                 case COR_E_THREADINTERRUPTED:
1559                                         return new ThreadInterruptedException ();
1560                                 case COR_E_THREADSTATE:
1561                                         return new ThreadStateException ();
1562 //                              case COR_E_THREADSTOP:
1563 //                                      ThreadStopException does not exist
1564 //                                      return new System.Threading.ThreadStopException ();
1565                                 case COR_E_TYPELOAD:
1566                                         return new TypeLoadException ();
1567                                 // MSDN lists COR_E_TYPELOAD twice with different exceptions.
1568                                 // return new EntryPointNotFoundException ();
1569                                 case COR_E_TYPEINITIALIZATION:
1570                                         return new TypeInitializationException("", null);
1571                                 case COR_E_VERIFICATION:
1572                                         return new VerificationException ();
1573 //                              case COR_E_WEAKREFERENCE:
1574 //                                      return new WeakReferenceException ();
1575 //                              case COR_E_VTABLECALLSNOTSUPPORTED:
1576 //                                      return new VTableCallsNotSupportedException ();
1577                         }
1578                         if (errorCode < 0)
1579                                 return new COMException ("", errorCode);
1580                         return null;
1581                 }
1582
1583 #if FEATURE_COMINTEROP
1584                 [DllImport ("oleaut32.dll", CharSet=CharSet.Unicode, EntryPoint = "SetErrorInfo")]
1585                 static extern int _SetErrorInfo (int dwReserved,
1586                         [MarshalAs(UnmanagedType.Interface)] IErrorInfo pIErrorInfo);
1587
1588                 [DllImport ("oleaut32.dll", CharSet=CharSet.Unicode, EntryPoint = "GetErrorInfo")]
1589                 static extern int _GetErrorInfo (int dwReserved,
1590                         [MarshalAs(UnmanagedType.Interface)] out IErrorInfo ppIErrorInfo);
1591
1592                 static bool SetErrorInfoNotAvailable;
1593                 static bool GetErrorInfoNotAvailable;
1594
1595                 internal static int SetErrorInfo (int dwReserved, IErrorInfo errorInfo)
1596                 {
1597                         int retVal = 0;
1598                         errorInfo = null;
1599
1600                         if (SetErrorInfoNotAvailable)
1601                                 return -1;
1602
1603                         try {
1604                                 retVal = _SetErrorInfo (dwReserved, errorInfo);
1605                         }
1606                         catch (Exception) {
1607                                 // ignore any exception - probably there's no suitable SetErrorInfo
1608                                 // method available.
1609                                 SetErrorInfoNotAvailable = true;
1610                         }
1611                         return retVal;
1612                 }
1613
1614                 internal static int GetErrorInfo (int dwReserved, out IErrorInfo errorInfo)
1615                 {
1616                         int retVal = 0;
1617                         errorInfo = null;
1618
1619                         if (GetErrorInfoNotAvailable)
1620                                 return -1;
1621
1622                         try {
1623                                 retVal = _GetErrorInfo (dwReserved, out errorInfo);
1624                         }
1625                         catch (Exception) {
1626                                 // ignore any exception - probably there's no suitable GetErrorInfo
1627                                 // method available.
1628                                 GetErrorInfoNotAvailable = true;
1629                         }
1630                         return retVal;
1631                 }
1632 #endif
1633                 public static Exception GetExceptionForHR (int errorCode)
1634                 {
1635                         return GetExceptionForHR (errorCode, IntPtr.Zero);
1636                 }
1637
1638                 public static Exception GetExceptionForHR (int errorCode, IntPtr errorInfo)
1639                 {
1640 #if FEATURE_COMINTEROP
1641                         IErrorInfo info = null;
1642                         if (errorInfo != (IntPtr)(-1)) {
1643                                 if (errorInfo == IntPtr.Zero) {
1644                                         if (GetErrorInfo (0, out info) != 0) {
1645                                                 info  = null;
1646                                         }
1647                                 } else {
1648                                         info  = Marshal.GetObjectForIUnknown (errorInfo) as IErrorInfo;
1649                                 }
1650                         }
1651
1652                         if (info is ManagedErrorInfo && ((ManagedErrorInfo) info).Exception._HResult == errorCode) {
1653                                 return ((ManagedErrorInfo) info).Exception;
1654                         }
1655
1656                         Exception e = ConvertHrToException (errorCode);
1657                         if (info != null && e != null) {
1658                                 uint helpContext;
1659                                 info.GetHelpContext (out helpContext);
1660                                 string str;
1661                                 info.GetSource (out str);
1662                                 e.Source = str;
1663                                 info.GetDescription (out str);
1664                                 e.SetMessage (str);
1665                                 info.GetHelpFile (out str);
1666
1667                                 if (helpContext == 0) {
1668                                         e.HelpLink = str;
1669                                 } else {
1670                                         e.HelpLink = string.Format ("{0}#{1}", str, helpContext);
1671                                 }
1672                         }
1673                         return e;
1674 #else
1675                         return ConvertHrToException (errorCode);
1676 #endif
1677                 }
1678
1679                 public static int FinalReleaseComObject (object o)
1680                 {
1681                         while (ReleaseComObject (o) != 0);
1682                         return 0;
1683                 }
1684
1685                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1686                 private static extern Delegate GetDelegateForFunctionPointerInternal (IntPtr ptr, Type t);
1687
1688                 public static Delegate GetDelegateForFunctionPointer (IntPtr ptr, Type t)
1689                 {
1690                         if (t == null)
1691                                 throw new ArgumentNullException ("t");
1692                         if (!t.IsSubclassOf (typeof (MulticastDelegate)) || (t == typeof (MulticastDelegate)))
1693                                 throw new ArgumentException ("Type is not a delegate", "t");
1694                         if (t.IsGenericType)
1695                                 throw new ArgumentException ("The specified Type must not be a generic type definition.");
1696                         if (ptr == IntPtr.Zero)
1697                                 throw new ArgumentNullException ("ptr");
1698
1699                         return GetDelegateForFunctionPointerInternal (ptr, t);
1700                 }
1701
1702                 public static TDelegate GetDelegateForFunctionPointer<TDelegate> (IntPtr ptr) {
1703                         return (TDelegate) (object) GetDelegateForFunctionPointer (ptr, typeof (TDelegate));
1704                 }
1705
1706                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1707                 private static extern IntPtr GetFunctionPointerForDelegateInternal (Delegate d);
1708                 
1709                 public static IntPtr GetFunctionPointerForDelegate (Delegate d)
1710                 {
1711                         if (d == null)
1712                                 throw new ArgumentNullException ("d");
1713                         
1714                         return GetFunctionPointerForDelegateInternal (d);
1715                 }
1716
1717                 public static IntPtr GetFunctionPointerForDelegate<TDelegate> (TDelegate d) {
1718                         if (d == null)
1719                                 throw new ArgumentNullException ("d");
1720                         
1721                         return GetFunctionPointerForDelegateInternal ((Delegate)(object)d);
1722                 }
1723
1724                 internal static void SetLastWin32Error (int error)
1725                 {
1726                 }
1727         }
1728 }