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