Merge pull request #3460 from akoeplinger/remove-net_4_5-ifdef
[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 (e == null) return 0;
426
427 #if FEATURE_COMINTEROP
428                         var errorInfo = new ManagedErrorInfo(e);
429                         SetErrorInfo (0, errorInfo);
430 #endif
431
432                         return e._HResult;
433                 }
434
435                 [MonoTODO]
436                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
437                 public static int GetHRForLastWin32Error()
438                 {
439 #if FULL_AOT_RUNTIME
440                         throw new PlatformNotSupportedException ();
441 #else
442                         throw new NotImplementedException ();
443 #endif
444                 }
445
446 #if !FULL_AOT_RUNTIME
447                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
448                 private extern static IntPtr GetIDispatchForObjectInternal (object o);
449
450                 public static IntPtr GetIDispatchForObject (object o)
451                 {
452                         IntPtr pUnk = GetIDispatchForObjectInternal (o);
453                         // Internal method does not AddRef
454                         AddRef (pUnk);
455                         return pUnk;
456                 }
457
458                 [MonoTODO]
459                 public static IntPtr GetIDispatchForObjectInContext (object o)
460                 {
461                         throw new NotImplementedException ();
462                 }
463
464                 [MonoTODO]
465                 public static IntPtr GetITypeInfoForType (Type t)
466                 {
467                         throw new NotImplementedException ();
468                 }
469
470                 [MonoTODO]
471                 public static IntPtr GetIUnknownForObjectInContext (object o)
472                 {
473                         throw new NotImplementedException ();
474                 }
475
476                 [MonoTODO]
477                 [Obsolete ("This method has been deprecated")]
478                 public static IntPtr GetManagedThunkForUnmanagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
479                 {
480                         throw new NotImplementedException ();
481                 }
482
483                 [MonoTODO]
484                 public static MemberInfo GetMethodInfoForComSlot (Type t, int slot, ref ComMemberType memberType)
485                 {
486                         throw new NotImplementedException ();
487                 }
488
489                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
490                 private extern static IntPtr GetIUnknownForObjectInternal (object o);
491
492 #endif // !FULL_AOT_RUNTIME
493
494                 public static IntPtr GetIUnknownForObject (object o)
495                 {
496 #if FULL_AOT_RUNTIME
497                         throw new PlatformNotSupportedException ();
498 #else
499                         IntPtr pUnk = GetIUnknownForObjectInternal (o);
500                         // Internal method does not AddRef
501                         AddRef (pUnk);
502                         return pUnk;
503 #endif
504                 }
505
506                 public static void GetNativeVariantForObject (object obj, IntPtr pDstNativeVariant)
507                 {
508 #if FULL_AOT_RUNTIME
509                         throw new PlatformNotSupportedException ();
510 #else
511                         Variant vt = new Variant();
512                         vt.SetValue(obj);
513                         Marshal.StructureToPtr(vt, pDstNativeVariant, false);
514 #endif
515                 }
516
517                 public static void GetNativeVariantForObject<T> (T obj, IntPtr pDstNativeVariant) {
518                         GetNativeVariantForObject ((object)obj, pDstNativeVariant);
519                 }
520
521 #if !MOBILE && !FULL_AOT_RUNTIME
522                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
523                 private static extern object GetObjectForCCW (IntPtr pUnk);
524 #endif
525
526                 public static object GetObjectForIUnknown (IntPtr pUnk)
527                 {
528 #if MOBILE || FULL_AOT_RUNTIME
529                         throw new PlatformNotSupportedException ();
530 #else
531                         object obj = GetObjectForCCW (pUnk);
532                         // was not a CCW
533                         if (obj == null) {
534                                 ComInteropProxy proxy = ComInteropProxy.GetProxy (pUnk, typeof (__ComObject));
535                                 obj = proxy.GetTransparentProxy ();
536                         }
537                         return obj;
538 #endif
539                 }
540
541                 public static object GetObjectForNativeVariant (IntPtr pSrcNativeVariant)
542                 {
543 #if FULL_AOT_RUNTIME
544                         throw new PlatformNotSupportedException ();
545 #else
546                         Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
547                         return vt.GetValue();
548 #endif
549                 }
550
551                 public static T GetObjectForNativeVariant<T> (IntPtr pSrcNativeVariant)
552                 {
553 #if FULL_AOT_RUNTIME
554                         throw new PlatformNotSupportedException ();
555 #else
556                         Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
557                         return (T)vt.GetValue();
558 #endif
559                 }
560
561                 public static object[] GetObjectsForNativeVariants (IntPtr aSrcNativeVariant, int cVars)
562                 {
563 #if FULL_AOT_RUNTIME
564                         throw new PlatformNotSupportedException ();
565 #else
566                         if (cVars < 0)
567                                 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
568                         object[] objects = new object[cVars];
569                         for (int i = 0; i < cVars; i++)
570                                 objects[i] = GetObjectForNativeVariant ((IntPtr)(aSrcNativeVariant.ToInt64 () +
571                                         i * SizeOf (typeof(Variant))));
572                         return objects;
573 #endif
574                 }
575
576                 public static T[] GetObjectsForNativeVariants<T> (IntPtr aSrcNativeVariant, int cVars)
577                 {
578 #if FULL_AOT_RUNTIME
579                         throw new PlatformNotSupportedException ();
580 #else
581                         if (cVars < 0)
582                                 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
583                         T[] objects = new T[cVars];
584                         for (int i = 0; i < cVars; i++)
585                                 objects[i] = GetObjectForNativeVariant<T> ((IntPtr)(aSrcNativeVariant.ToInt64 () +
586                                         i * SizeOf (typeof(Variant))));
587                         return objects;
588 #endif
589                 }
590
591                 [MonoTODO]
592                 public static int GetStartComSlot (Type t)
593                 {
594 #if FULL_AOT_RUNTIME
595                         throw new PlatformNotSupportedException ();
596 #else
597                         throw new NotImplementedException ();
598 #endif
599                 }
600
601 #if !FULL_AOT_RUNTIME
602                 [MonoTODO]
603                 [Obsolete ("This method has been deprecated")]
604                 public static Thread GetThreadFromFiberCookie (int cookie)
605                 {
606                         throw new NotImplementedException ();
607                 }
608
609                 public static object GetTypedObjectForIUnknown (IntPtr pUnk, Type t)
610                 {
611                         ComInteropProxy proxy = new ComInteropProxy (pUnk, t);
612                         __ComObject co = (__ComObject)proxy.GetTransparentProxy ();
613                         foreach (Type itf in t.GetInterfaces ()) {
614                                 if ((itf.Attributes & TypeAttributes.Import) == TypeAttributes.Import) {
615                                         if (co.GetInterface (itf) == IntPtr.Zero)
616                                                 return null;
617                                 }
618                         }
619                         return co;
620                 }
621
622                 [MonoTODO]
623                 public static Type GetTypeForITypeInfo (IntPtr piTypeInfo)
624                 {
625                         throw new NotImplementedException ();
626                 }
627
628                 [Obsolete]
629                 [MonoTODO]
630                 public static string GetTypeInfoName (UCOMITypeInfo pTI)
631                 {
632                         throw new NotImplementedException ();
633                 }
634
635                 [Obsolete]
636                 [MonoTODO]
637                 public static Guid GetTypeLibGuid (UCOMITypeLib pTLB)
638                 {
639                         throw new NotImplementedException ();
640                 }
641
642                 [MonoTODO]
643                 public static Guid GetTypeLibGuid (ITypeLib typelib)
644                 {
645                         throw new NotImplementedException ();
646                 }
647
648                 [MonoTODO]
649                 public static Guid GetTypeLibGuidForAssembly (Assembly asm)
650                 {
651                         throw new NotImplementedException ();
652                 }
653
654                 [Obsolete]
655                 [MonoTODO]
656                 public static int GetTypeLibLcid (UCOMITypeLib pTLB)
657                 {
658                         throw new NotImplementedException ();
659                 }
660
661                 [MonoTODO]
662                 public static int GetTypeLibLcid (ITypeLib typelib)
663                 {
664                         throw new NotImplementedException ();
665                 }
666
667                 [Obsolete]
668                 [MonoTODO]
669                 public static string GetTypeLibName (UCOMITypeLib pTLB)
670                 {
671                         throw new NotImplementedException ();
672                 }
673
674                 [MonoTODO]
675                 public static string GetTypeLibName (ITypeLib typelib)
676                 {
677                         throw new NotImplementedException ();
678                 }
679
680                 [MonoTODO]
681                 public static void GetTypeLibVersionForAssembly (Assembly inputAssembly, out int majorVersion, out int minorVersion)
682                 {
683                         throw new NotImplementedException ();
684                 }
685
686                 [MonoTODO]
687                 [Obsolete ("This method has been deprecated")]
688                 public static IntPtr GetUnmanagedThunkForManagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
689                 {
690                         throw new NotImplementedException ();
691                 }
692
693                 [MonoTODO]
694                 public static bool IsTypeVisibleFromCom (Type t)
695                 {
696                         throw new NotImplementedException ();
697                 }
698
699                 [MonoTODO]
700                 public static int NumParamBytes (MethodInfo m)
701                 {
702                         throw new NotImplementedException ();
703                 }
704 #endif // !FULL_AOT_RUNTIME
705
706                 public static Type GetTypeFromCLSID (Guid clsid)
707                 {
708                         throw new PlatformNotSupportedException ();
709                 }
710
711                 public static string GetTypeInfoName (ITypeInfo typeInfo)
712                 {
713                         throw new PlatformNotSupportedException ();
714                 }
715
716                 public static object GetUniqueObjectForIUnknown (IntPtr unknown)
717                 {
718                         throw new PlatformNotSupportedException ();
719                 }
720
721 #if !MOBILE
722                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
723                 public extern static bool IsComObject (object o);
724 #else
725                 public static bool IsComObject (object o)
726                 {
727                         throw new PlatformNotSupportedException ();
728                 }
729 #endif
730
731                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
732                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
733                 public static extern int GetLastWin32Error();
734
735                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
736                 public extern static IntPtr OffsetOf (Type t, string fieldName);
737
738                 public static IntPtr OffsetOf<T> (string fieldName) {
739                         return OffsetOf (typeof (T), fieldName);
740                 }
741
742                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
743                 public extern static void Prelink (MethodInfo m);
744
745                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
746                 public extern static void PrelinkAll (Type c);
747
748                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
749                 public extern static string PtrToStringAnsi (IntPtr ptr);
750                 
751                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
752                 public extern static string PtrToStringAnsi (IntPtr ptr, int len);
753
754                 public static string PtrToStringAuto (IntPtr ptr)
755                 {
756                         return SystemDefaultCharSize == 2
757                                 ? PtrToStringUni (ptr) : PtrToStringAnsi (ptr);
758                 }
759                 
760                 public static string PtrToStringAuto (IntPtr ptr, int len)
761                 {
762                         return SystemDefaultCharSize == 2
763                                 ? PtrToStringUni (ptr, len) : PtrToStringAnsi (ptr, len);
764                 }
765
766                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
767                 public extern static string PtrToStringUni (IntPtr ptr);
768
769                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
770                 public extern static string PtrToStringUni (IntPtr ptr, int len);
771
772 #if !MOBILE
773                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
774                 public extern static string PtrToStringBSTR (IntPtr ptr);
775 #else
776                 public static string PtrToStringBSTR (IntPtr ptr)
777                 {
778                         throw new NotImplementedException ();
779                 }
780 #endif
781                 
782                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
783                 [ComVisible (true)]
784                 public extern static void PtrToStructure (IntPtr ptr, object structure);
785
786                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
787                 [ComVisible (true)]
788                 public extern static object PtrToStructure (IntPtr ptr, Type structureType);
789
790                 public static void PtrToStructure<T> (IntPtr ptr, T structure) {
791                         PtrToStructure (ptr, (object)structure);
792                 }
793
794                 public static T PtrToStructure<T> (IntPtr ptr) {
795                         return (T) PtrToStructure (ptr, typeof (T));
796                 }
797
798 #if !MOBILE
799                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
800                 private extern static int QueryInterfaceInternal (IntPtr pUnk, ref Guid iid, out IntPtr ppv);
801 #endif
802
803                 public static int QueryInterface (IntPtr pUnk, ref Guid iid, out IntPtr ppv)
804                 {
805 #if !MOBILE
806                         if (pUnk == IntPtr.Zero)
807                                 throw new ArgumentException ("Value cannot be null.", "pUnk");
808                         return QueryInterfaceInternal (pUnk, ref iid, out ppv);
809 #else
810                         throw new NotImplementedException ();
811 #endif
812                 }
813
814                 public static byte ReadByte (IntPtr ptr)
815                 {
816                         unsafe {
817                                 return *(byte*)ptr;
818                         }
819                 }
820
821                 public static byte ReadByte (IntPtr ptr, int ofs) {
822                         unsafe {
823                                 return *((byte*)ptr + ofs);
824                         }
825                 }
826
827                 [MonoTODO]
828                 [SuppressUnmanagedCodeSecurity]
829                 public static byte ReadByte ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
830                 {
831                         throw new NotImplementedException ();
832                 }
833
834                 public unsafe static short ReadInt16 (IntPtr ptr)
835                 {
836                         byte *addr = (byte *) ptr;
837                         
838                         // The mono JIT can't inline this due to the hight number of calls
839                         // return ReadInt16 (ptr, 0);
840                         
841                         if (((uint)addr & 1) == 0) 
842                                 return *(short*)addr;
843
844                         short s;
845                         Buffer.Memcpy ((byte*)&s, (byte*)ptr, 2);
846                         return s;
847                 }
848
849                 public unsafe static short ReadInt16 (IntPtr ptr, int ofs)
850                 {
851                         byte *addr = ((byte *) ptr) + ofs;
852
853                         if (((uint) addr & 1) == 0)
854                                 return *(short*)addr;
855
856                         short s;
857                         Buffer.Memcpy ((byte*)&s, addr, 2);
858                         return s;
859                 }
860
861                 [MonoTODO]
862                 [SuppressUnmanagedCodeSecurity]
863                 public static short ReadInt16 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
864                 {
865                         throw new NotImplementedException ();
866                 }
867
868                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
869                 public unsafe static int ReadInt32 (IntPtr ptr)
870                 {
871                         byte *addr = (byte *) ptr;
872                         
873                         if (((uint)addr & 3) == 0) 
874                                 return *(int*)addr;
875
876                         int s;
877                         Buffer.Memcpy ((byte*)&s, addr, 4);
878                         return s;
879                 }
880
881                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
882                 public unsafe static int ReadInt32 (IntPtr ptr, int ofs)
883                 {
884                         byte *addr = ((byte *) ptr) + ofs;
885                         
886                         if ((((int) addr) & 3) == 0)
887                                 return *(int*)addr;
888                         else {
889                                 int s;
890                                 Buffer.Memcpy ((byte*)&s, addr, 4);
891                                 return s;
892                         }
893                 }
894
895                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
896                 [MonoTODO]
897                 [SuppressUnmanagedCodeSecurity]
898                 public static int ReadInt32 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
899                 {
900                         throw new NotImplementedException ();
901                 }
902
903                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
904                 public unsafe static long ReadInt64 (IntPtr ptr)
905                 {
906                         byte *addr = (byte *) ptr;
907                                 
908                         // The real alignment might be 4 on some platforms, but this is just an optimization,
909                         // so it doesn't matter.
910                         if (((uint) addr & 7) == 0)
911                                 return *(long*)ptr;
912
913                         long s;
914                         Buffer.Memcpy ((byte*)&s, addr, 8);
915                         return s;
916                 }
917
918                 public unsafe static long ReadInt64 (IntPtr ptr, int ofs)
919                 {
920                         byte *addr = ((byte *) ptr) + ofs;
921
922                         if (((uint) addr & 7) == 0)
923                                 return *(long*)addr;
924                         
925                         long s;
926                         Buffer.Memcpy ((byte*)&s, addr, 8);
927                         return s;
928                 }
929
930                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
931                 [MonoTODO]
932                 [SuppressUnmanagedCodeSecurity]
933                 public static long ReadInt64 ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
934                 {
935                         throw new NotImplementedException ();
936                 }
937
938                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
939                 public static IntPtr ReadIntPtr (IntPtr ptr)
940                 {
941                         if (IntPtr.Size == 4)
942                                 return (IntPtr)ReadInt32 (ptr);
943                         else
944                                 return (IntPtr)ReadInt64 (ptr);
945                 }
946                 
947                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
948                 public static IntPtr ReadIntPtr (IntPtr ptr, int ofs)
949                 {
950                         if (IntPtr.Size == 4)
951                                 return (IntPtr)ReadInt32 (ptr, ofs);
952                         else
953                                 return (IntPtr)ReadInt64 (ptr, ofs);
954                 }
955
956                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
957                 [MonoTODO]
958                 public static IntPtr ReadIntPtr ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
959                 {
960                         throw new NotImplementedException ();
961                 }
962
963                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
964                 public extern static IntPtr ReAllocCoTaskMem (IntPtr pv, int cb);
965
966                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
967                 public extern static IntPtr ReAllocHGlobal (IntPtr pv, IntPtr cb);
968
969 #if !MOBILE
970                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
971                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
972                 private extern static int ReleaseInternal (IntPtr pUnk);
973 #endif
974
975                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
976                 public static int Release (IntPtr pUnk)
977                 {
978 #if !MOBILE
979                         if (pUnk == IntPtr.Zero)
980                                 throw new ArgumentException ("Value cannot be null.", "pUnk");
981
982                         return ReleaseInternal (pUnk);
983 #else
984                         throw new NotImplementedException ();
985 #endif
986                 }
987
988 #if !FULL_AOT_RUNTIME
989                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
990                 private extern static int ReleaseComObjectInternal (object co);
991 #endif
992
993                 public static int ReleaseComObject (object o)
994                 {
995 #if FULL_AOT_RUNTIME
996                         throw new PlatformNotSupportedException ();
997 #else
998                         if (o == null)
999                                 throw new ArgumentException ("Value cannot be null.", "o");
1000                         if (!IsComObject (o))
1001                                 throw new ArgumentException ("Value must be a Com object.", "o");
1002                         return ReleaseComObjectInternal (o);
1003 #endif
1004                 }
1005
1006 #if !FULL_AOT_RUNTIME
1007                 [Obsolete]
1008                 [MonoTODO]
1009                 public static void ReleaseThreadCache()
1010                 {
1011                         throw new NotImplementedException ();
1012                 }
1013
1014                 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
1015                 public static bool SetComObjectData (object obj, object key, object data)
1016                 {
1017                         throw new NotSupportedException ("MSDN states user code should never need to call this method.");
1018                 }
1019 #endif
1020
1021                 [ComVisible (true)]
1022                 public static int SizeOf (object structure)
1023                 {
1024                         return SizeOf (structure.GetType ());
1025                 }
1026
1027                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1028                 public extern static int SizeOf (Type t);
1029
1030                 public static int SizeOf<T> () {
1031                         return SizeOf (typeof (T));
1032                 }
1033
1034                 public static int SizeOf<T> (T structure) {
1035                         return SizeOf (structure.GetType ());
1036                 }
1037
1038                 internal static uint SizeOfType (Type type)
1039                 {
1040                         return (uint) SizeOf (type);
1041                 }
1042
1043                 internal static uint AlignedSizeOf<T> () where T : struct
1044                 {
1045                         uint size = SizeOfType (typeof (T));
1046                         if (size == 1 || size == 2)
1047                                 return size;
1048                         if (IntPtr.Size == 8 && size == 4)
1049                                 return size;
1050                         return (size + 3) & (~((uint)3));
1051                 }
1052
1053                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1054                 public extern static IntPtr StringToBSTR (string s);
1055
1056                 //
1057                 // I believe this is wrong, because in Mono and in P/Invoke
1058                 // we treat "Ansi" conversions as UTF-8 conversions, while
1059                 // this one does not do this
1060                 //
1061                 public static IntPtr StringToCoTaskMemAnsi (string s)
1062                 {
1063                         int length = s.Length + 1;
1064                         IntPtr ctm = AllocCoTaskMem (length);
1065
1066                         byte[] asBytes = new byte[length];
1067                         for (int i = 0; i < s.Length; i++)
1068                                 asBytes[i] = (byte)s[i];
1069                         asBytes[s.Length] = 0;
1070
1071                         copy_to_unmanaged (asBytes, 0, ctm, length);
1072                         return ctm;
1073                 }
1074
1075                 public static IntPtr StringToCoTaskMemAuto (string s)
1076                 {
1077                         return SystemDefaultCharSize == 2
1078                                 ? StringToCoTaskMemUni (s) : StringToCoTaskMemAnsi (s);
1079                 }
1080
1081                 public static IntPtr StringToCoTaskMemUni (string s)
1082                 {
1083                         int length = s.Length + 1;
1084                         IntPtr ctm = AllocCoTaskMem (length * 2);
1085                         
1086                         char[] asChars = new char[length];
1087                         s.CopyTo (0, asChars, 0, s.Length);
1088                         asChars[s.Length] = '\0';
1089
1090                         copy_to_unmanaged (asChars, 0, ctm, length);
1091                         return ctm;
1092                 }
1093
1094                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1095                 public extern static IntPtr StringToHGlobalAnsi (string s);
1096
1097                 public static IntPtr StringToHGlobalAuto (string s)
1098                 {
1099                         return SystemDefaultCharSize == 2
1100                                 ? StringToHGlobalUni (s) : StringToHGlobalAnsi (s);
1101                 }
1102
1103                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1104                 public extern static IntPtr StringToHGlobalUni (string s);
1105
1106                 public static IntPtr SecureStringToBSTR (SecureString s)
1107                 {
1108                         if (s == null)
1109                                 throw new ArgumentNullException ("s");
1110
1111                         byte[] buffer = s.GetBuffer ();
1112                         int len = s.Length;
1113                         
1114                         // SecureString doesn't take endian-ness into account. 
1115                         // Therefore swap bytes here before we send it to c-side if little-endian.
1116                         if (BitConverter.IsLittleEndian) {
1117                                 for (int i = 0; i < buffer.Length; i += 2) {
1118                                         byte b = buffer[i];
1119                                         buffer[i] = buffer[i + 1];
1120                                         buffer[i + 1] = b;
1121                                 }
1122                         }
1123                         return BufferToBSTR (buffer, len);
1124         }
1125
1126                 public static IntPtr SecureStringToCoTaskMemAnsi (SecureString s)
1127                 {
1128                         if (s == null)
1129                                 throw new ArgumentNullException ("s");
1130                         int len = s.Length;
1131                         IntPtr ctm = AllocCoTaskMem (len + 1);
1132                         byte [] copy = new byte [len+1];
1133
1134                         try {
1135                                 byte [] buffer = s.GetBuffer ();
1136                                 int i = 0, j = 0;
1137                                 for (; i < len; i++, j += 2){
1138                                         copy [i] = buffer [j+1];
1139                                         buffer [j] = 0;
1140                                         buffer [j+1] = 0;
1141                                 }
1142                                 copy [i] = 0;
1143                                 copy_to_unmanaged (copy, 0, ctm, len+1);
1144                         } finally {
1145                                 // Ensure that we clear the buffer.
1146                                 for (int i = len; i > 0; ){
1147                                         i--;
1148                                         copy [i] = 0;
1149                                 }
1150                         }
1151                         return ctm;
1152                 }
1153
1154                 public static IntPtr SecureStringToCoTaskMemUnicode (SecureString s)
1155                 {
1156                         if (s == null)
1157                                 throw new ArgumentNullException ("s");
1158                         int len = s.Length;
1159                         IntPtr ctm = AllocCoTaskMem (len * 2 + 2);
1160                         byte [] buffer = null;
1161                         try {
1162                                 buffer = s.GetBuffer ();
1163                                 for (int i = 0; i < len; i++)
1164                                         WriteInt16 (ctm, i * 2, (short) ((buffer [(i*2)] << 8) | (buffer [i*2+1])));
1165                                 WriteInt16 (ctm, buffer.Length, 0);
1166                         } finally {
1167                                 if (buffer != null)
1168                                         for (int i = buffer.Length; i > 0; ){
1169                                                 i--;
1170                                                 buffer [i] = 0;
1171                                         }
1172                         }
1173                         return ctm;
1174                 }
1175
1176                 public static IntPtr SecureStringToGlobalAllocAnsi (SecureString s)
1177                 {
1178                         if (s == null)
1179                                 throw new ArgumentNullException ("s");
1180                         return SecureStringToCoTaskMemAnsi (s);
1181                 }
1182
1183                 public static IntPtr SecureStringToGlobalAllocUnicode (SecureString s)
1184                 {
1185                         if (s == null)
1186                                 throw new ArgumentNullException ("s");
1187                         return SecureStringToCoTaskMemUnicode (s);
1188                 }
1189
1190                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
1191                 [ComVisible (true)]
1192                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1193                 public extern static void StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld);
1194
1195                 public static void StructureToPtr<T> (T structure, IntPtr ptr, bool fDeleteOld) {
1196                         StructureToPtr ((object)structure, ptr, fDeleteOld);
1197                 }
1198
1199                 public static void ThrowExceptionForHR (int errorCode) {
1200                         Exception ex = GetExceptionForHR (errorCode);
1201                         if (ex != null)
1202                                 throw ex;
1203                 }
1204
1205                 public static void ThrowExceptionForHR (int errorCode, IntPtr errorInfo) {
1206                         Exception ex = GetExceptionForHR (errorCode, errorInfo);
1207                         if (ex != null)
1208                                 throw ex;
1209                 }
1210
1211
1212                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1213                 public extern static IntPtr BufferToBSTR (Array ptr, int slen);
1214
1215                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1216                 public extern static IntPtr UnsafeAddrOfPinnedArrayElement (Array arr, int index);
1217
1218                 public static IntPtr UnsafeAddrOfPinnedArrayElement<T> (T[] arr, int index) {
1219                         return UnsafeAddrOfPinnedArrayElement ((Array)arr, index);
1220                 }
1221
1222                 public static void WriteByte (IntPtr ptr, byte val)
1223                 {
1224                         unsafe {
1225                                 *(byte*)ptr = val;
1226                         }
1227                 }
1228
1229                 public static void WriteByte (IntPtr ptr, int ofs, byte val) {
1230                         unsafe {
1231                                 *(byte*)(IntPtr.Add (ptr, ofs)) = val;
1232                         }
1233                 }
1234
1235                 [MonoTODO]
1236                 [SuppressUnmanagedCodeSecurity]
1237                 public static void WriteByte ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, byte val)
1238                 {
1239                         throw new NotImplementedException ();
1240                 }
1241
1242                 public static unsafe void WriteInt16 (IntPtr ptr, short val)
1243                 {
1244                         byte *addr = (byte *) ptr;
1245                         
1246                         if (((uint)addr & 1) == 0)
1247                                 *(short*)addr = val;
1248                         else
1249                                 Buffer.Memcpy (addr, (byte*)&val, 2);
1250                 }
1251
1252                 public static unsafe void WriteInt16 (IntPtr ptr, int ofs, short val)
1253                 {
1254                         byte *addr = ((byte *) ptr) + ofs;
1255
1256                         if (((uint)addr & 1) == 0)
1257                                 *(short*)addr = val;
1258                         else {
1259                                 Buffer.Memcpy (addr, (byte*)&val, 2);
1260                         }
1261                 }
1262
1263                 [MonoTODO]
1264                 [SuppressUnmanagedCodeSecurity]
1265                 public static void WriteInt16 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, short val)
1266                 {
1267                         throw new NotImplementedException ();
1268                 }
1269
1270                 public static void WriteInt16 (IntPtr ptr, char val)
1271                 {
1272                         WriteInt16 (ptr, 0, (short)val);
1273                 }
1274
1275                 public static void WriteInt16 (IntPtr ptr, int ofs, char val)
1276                 {
1277                         WriteInt16 (ptr, ofs, (short)val);
1278                 }
1279
1280                 [MonoTODO]
1281                 public static void WriteInt16([In, Out] object ptr, int ofs, char val)
1282                 {
1283                         throw new NotImplementedException ();
1284                 }
1285
1286                 public static unsafe void WriteInt32 (IntPtr ptr, int val)
1287                 {
1288                         byte *addr = (byte *) ptr;
1289                         
1290                         if (((uint)addr & 3) == 0) 
1291                                 *(int*)addr = val;
1292                         else {
1293                                 Buffer.Memcpy (addr, (byte*)&val, 4);
1294                         }
1295                 }
1296
1297                 public unsafe static void WriteInt32 (IntPtr ptr, int ofs, int val)
1298                 {
1299                         byte *addr = ((byte *) ptr) + ofs;
1300
1301                         if (((uint)addr & 3) == 0) 
1302                                 *(int*)addr = val;
1303                         else {
1304                                 Buffer.Memcpy (addr, (byte*)&val, 4);
1305                         }
1306                 }
1307
1308                 [MonoTODO]
1309                 [SuppressUnmanagedCodeSecurity]
1310                 public static void WriteInt32([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, int val)
1311                 {
1312                         throw new NotImplementedException ();
1313                 }
1314
1315                 public static unsafe void WriteInt64 (IntPtr ptr, long val)
1316                 {
1317                         byte *addr = (byte *) ptr;
1318                         
1319                         // The real alignment might be 4 on some platforms, but this is just an optimization,
1320                         // so it doesn't matter.
1321                         if (((uint)addr & 7) == 0) 
1322                                 *(long*)addr = val;
1323                         else 
1324                                 Buffer.Memcpy (addr, (byte*)&val, 8);
1325                 }
1326
1327                 public static unsafe void WriteInt64 (IntPtr ptr, int ofs, long val)
1328                 {
1329                         byte *addr = ((byte *) ptr) + ofs;
1330
1331                         // The real alignment might be 4 on some platforms, but this is just an optimization,
1332                         // so it doesn't matter.
1333                         if (((uint)addr & 7) == 0) 
1334                                 *(long*)addr = val;
1335                         else 
1336                                 Buffer.Memcpy (addr, (byte*)&val, 8);
1337                 }
1338
1339                 [MonoTODO]
1340                 [SuppressUnmanagedCodeSecurity]
1341                 public static void WriteInt64 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, long val)
1342                 {
1343                         throw new NotImplementedException ();
1344                 }
1345
1346                 public static void WriteIntPtr (IntPtr ptr, IntPtr val)
1347                 {
1348                         if (IntPtr.Size == 4)
1349                                 WriteInt32 (ptr, (int)val);
1350                         else
1351                                 WriteInt64 (ptr, (long)val);
1352                 }
1353
1354                 public static void WriteIntPtr (IntPtr ptr, int ofs, IntPtr val)
1355                 {
1356                         if (IntPtr.Size == 4)
1357                                 WriteInt32 (ptr, ofs, (int)val);
1358                         else
1359                                 WriteInt64 (ptr, ofs, (long)val);
1360                 }
1361
1362                 [MonoTODO]
1363                 public static void WriteIntPtr([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, IntPtr val)
1364                 {
1365                         throw new NotImplementedException ();
1366                 }
1367
1368                 private static Exception ConvertHrToException (int errorCode)
1369                 {
1370                         const int MSEE_E_APPDOMAINUNLOADED = unchecked ((int)0x80131014L);
1371                         const int COR_E_APPLICATION = unchecked ((int)0x80131600L);
1372                         const int E_INVALIDARG = unchecked ((int)0x80070057);
1373                         const int COR_E_ARGUMENTOUTOFRANGE = unchecked ((int)0x80131502L);
1374                         const int COR_E_ARITHMETIC = unchecked ((int)0x80070216);
1375                         const int COR_E_ARRAYTYPEMISMATCH = unchecked ((int)0x80131503L);
1376                         const int COR_E_BADIMAGEFORMAT = unchecked ((int)0x8007000BL);
1377                         const int ERROR_BAD_FORMAT = unchecked ((int)0x0B);
1378                         //const int COR_E_COMEMULATE_ERROR = unchecked ((int)?);
1379                         const int COR_E_CONTEXTMARSHAL = unchecked ((int)0x80131504L);
1380                         //const int COR_E_CORE = unchecked ((int)?);
1381                         const int NTE_FAIL = unchecked ((int)0x80090020L);
1382                         const int COR_E_DIRECTORYNOTFOUND = unchecked ((int)0x80070003L);
1383                         const int ERROR_PATH_NOT_FOUND = unchecked ((int)0x03);
1384                         const int COR_E_DIVIDEBYZERO = unchecked ((int)0x80020012L);
1385                         const int COR_E_DUPLICATEWAITOBJECT = unchecked ((int)0x80131529L);
1386                         const int COR_E_ENDOFSTREAM = unchecked ((int)0x80070026L);
1387                         const int COR_E_TYPELOAD = unchecked ((int)0x80131522L);
1388                         const int COR_E_EXCEPTION = unchecked ((int)0x80131500L);
1389                         const int COR_E_EXECUTIONENGINE = unchecked ((int)0x80131506L);
1390                         const int COR_E_FIELDACCESS = unchecked ((int)0x80131507L);
1391                         const int COR_E_FILENOTFOUND = unchecked ((int)0x80070002L);
1392                         const int ERROR_FILE_NOT_FOUND = unchecked ((int)0x02);
1393                         const int COR_E_FORMAT = unchecked ((int)0x80131537L);
1394                         const int COR_E_INDEXOUTOFRANGE = unchecked ((int)0x80131508L);
1395                         const int COR_E_INVALIDCAST = unchecked ((int)0x80004002L);
1396                         const int COR_E_INVALIDCOMOBJECT = unchecked ((int)0x80131527L);
1397                         const int COR_E_INVALIDFILTERCRITERIA = unchecked ((int)0x80131601L);
1398                         const int COR_E_INVALIDOLEVARIANTTYPE = unchecked ((int)0x80131531L);
1399                         const int COR_E_INVALIDOPERATION = unchecked ((int)0x80131509L);
1400                         const int COR_E_IO = unchecked ((int)0x80131620L);
1401                         const int COR_E_MEMBERACCESS = unchecked ((int)0x8013151AL);
1402                         const int COR_E_METHODACCESS = unchecked ((int)0x80131510L);
1403                         const int COR_E_MISSINGFIELD = unchecked ((int)0x80131511L);
1404                         const int COR_E_MISSINGMANIFESTRESOURCE = unchecked ((int)0x80131532L);
1405                         const int COR_E_MISSINGMEMBER = unchecked ((int)0x80131512L);
1406                         const int COR_E_MISSINGMETHOD = unchecked ((int)0x80131513L);
1407                         const int COR_E_MULTICASTNOTSUPPORTED = unchecked ((int)0x80131514L);
1408                         const int COR_E_NOTFINITENUMBER = unchecked ((int)0x80131528L);
1409                         const int E_NOTIMPL = unchecked ((int)0x80004001L);
1410                         const int COR_E_NOTSUPPORTED = unchecked ((int)0x80131515L);
1411                         const int COR_E_NULLREFERENCE = unchecked ((int)0x80004003L);
1412                         const int E_OUTOFMEMORY = unchecked ((int)0x8007000EL);
1413                         const int COR_E_OVERFLOW = unchecked ((int)0x80131516L);
1414                         const int COR_E_PATHTOOLONG = unchecked ((int)0x800700CEL);
1415                         const int ERROR_FILENAME_EXCED_RANGE = unchecked ((int)0xCE);
1416                         const int COR_E_RANK = unchecked ((int)0x80131517L);
1417                         const int COR_E_REFLECTIONTYPELOAD = unchecked ((int)0x80131602L);
1418                         const int COR_E_REMOTING = unchecked ((int)0x8013150BL);
1419                         const int COR_E_SAFEARRAYTYPEMISMATCH = unchecked ((int)0x80131533L);
1420                         const int COR_E_SECURITY = unchecked ((int)0x8013150AL);
1421                         const int COR_E_SERIALIZATION = unchecked ((int)0x8013150CL);
1422                         const int COR_E_STACKOVERFLOW = unchecked ((int)0x800703E9L);
1423                         const int ERROR_STACK_OVERFLOW = unchecked ((int)0x03E9);
1424                         const int COR_E_SYNCHRONIZATIONLOCK = unchecked ((int)0x80131518L);
1425                         const int COR_E_SYSTEM = unchecked ((int)0x80131501L);
1426                         const int COR_E_TARGET = unchecked ((int)0x80131603L);
1427                         const int COR_E_TARGETINVOCATION = unchecked ((int)0x80131604L);
1428                         const int COR_E_TARGETPARAMCOUNT = unchecked ((int)0x8002000EL);
1429                         const int COR_E_THREADABORTED = unchecked ((int)0x80131530L);
1430                         const int COR_E_THREADINTERRUPTED = unchecked ((int)0x80131519L);
1431                         const int COR_E_THREADSTATE = unchecked ((int)0x80131520L);
1432                         const int COR_E_THREADSTOP = unchecked ((int)0x80131521L);
1433                         const int COR_E_TYPEINITIALIZATION = unchecked ((int)0x80131534L);
1434                         const int COR_E_VERIFICATION = unchecked ((int)0x8013150DL);
1435                         //const int COR_E_WEAKREFERENCE = unchecked ((int)?);
1436                         //const int COR_E_VTABLECALLSNOTSUPPORTED = unchecked ((int));
1437
1438                         switch (errorCode) {
1439                                 case MSEE_E_APPDOMAINUNLOADED:
1440                                         return new AppDomainUnloadedException ();
1441                                 case COR_E_APPLICATION:
1442                                         return new ApplicationException ();
1443                                 case E_INVALIDARG:
1444                                         return new ArgumentException ();
1445                                 case COR_E_ARGUMENTOUTOFRANGE:
1446                                         return new ArgumentOutOfRangeException ();
1447                                 case COR_E_ARITHMETIC:
1448                                         return new ArithmeticException ();
1449                                 case COR_E_ARRAYTYPEMISMATCH:
1450                                         return new ArrayTypeMismatchException ();
1451                                 case COR_E_BADIMAGEFORMAT:
1452                                 case ERROR_BAD_FORMAT:
1453                                         return new BadImageFormatException ();
1454 //                              case COR_E_COMEMULATE_ERROR:
1455 //                                      return new COMEmulateException ();
1456                                 case COR_E_CONTEXTMARSHAL:
1457                                         return new ContextMarshalException ();
1458 //                              case COR_E_CORE:
1459 //                                      return new CoreException ();
1460                                 case NTE_FAIL:
1461                                         return new System.Security.Cryptography.CryptographicException ();
1462                                 case COR_E_DIRECTORYNOTFOUND:
1463                                 case ERROR_PATH_NOT_FOUND:
1464                                         return new System.IO.DirectoryNotFoundException ();
1465                                 case COR_E_DIVIDEBYZERO:
1466                                         return new DivideByZeroException ();
1467                                 case COR_E_DUPLICATEWAITOBJECT:
1468                                         return new DuplicateWaitObjectException ();
1469                                 case COR_E_ENDOFSTREAM:
1470                                         return new System.IO.EndOfStreamException ();
1471                                 case COR_E_EXCEPTION:
1472                                         return new Exception ();
1473                                 case COR_E_EXECUTIONENGINE:
1474                                         return new ExecutionEngineException ();
1475                                 case COR_E_FIELDACCESS:
1476                                         return new FieldAccessException ();
1477                                 case COR_E_FILENOTFOUND:
1478                                 case ERROR_FILE_NOT_FOUND:
1479                                         return new System.IO.FileNotFoundException ();
1480                                 case COR_E_FORMAT:
1481                                         return new FormatException ();
1482                                 case COR_E_INDEXOUTOFRANGE:
1483                                         return new IndexOutOfRangeException ();
1484                                 case COR_E_INVALIDCAST:
1485                                 // E_NOINTERFACE has same value as COR_E_INVALIDCAST
1486                                         return new InvalidCastException ();
1487                                 case COR_E_INVALIDCOMOBJECT:
1488                                         return new InvalidComObjectException ();
1489                                 case COR_E_INVALIDFILTERCRITERIA:
1490                                         return new InvalidFilterCriteriaException ();
1491                                 case COR_E_INVALIDOLEVARIANTTYPE:
1492                                         return new InvalidOleVariantTypeException ();
1493                                 case COR_E_INVALIDOPERATION:
1494                                         return new InvalidOperationException ();
1495                                 case COR_E_IO:
1496                                         return new System.IO.IOException ();
1497                                 case COR_E_MEMBERACCESS:
1498                                         return new MemberAccessException ();
1499                                 case COR_E_METHODACCESS:
1500                                         return new MethodAccessException ();
1501                                 case COR_E_MISSINGFIELD:
1502                                         return new MissingFieldException ();
1503                                 case COR_E_MISSINGMANIFESTRESOURCE:
1504                                         return new System.Resources.MissingManifestResourceException ();
1505                                 case COR_E_MISSINGMEMBER:
1506                                         return new MissingMemberException ();
1507                                 case COR_E_MISSINGMETHOD:
1508                                         return new MissingMethodException ();
1509                                 case COR_E_MULTICASTNOTSUPPORTED:
1510                                         return new MulticastNotSupportedException ();
1511                                 case COR_E_NOTFINITENUMBER:
1512                                         return new NotFiniteNumberException ();
1513                                 case E_NOTIMPL:
1514                                         return new NotImplementedException ();
1515                                 case COR_E_NOTSUPPORTED:
1516                                         return new NotSupportedException ();
1517                                 case COR_E_NULLREFERENCE:
1518                                 // E_POINTER has the same value as COR_E_NULLREFERENCE
1519                                         return new NullReferenceException ();
1520                                 case E_OUTOFMEMORY:
1521                                 // COR_E_OUTOFMEMORY has the same value as E_OUTOFMEMORY
1522                                         return new OutOfMemoryException ();
1523                                 case COR_E_OVERFLOW:
1524                                         return new OverflowException ();
1525                                 case COR_E_PATHTOOLONG:
1526                                 case ERROR_FILENAME_EXCED_RANGE:
1527                                         return new System.IO.PathTooLongException ();
1528                                 case COR_E_RANK:
1529                                         return new RankException ();
1530                                 case COR_E_REFLECTIONTYPELOAD:
1531                                         return new System.Reflection.ReflectionTypeLoadException (new Type[] { }, new Exception[] { });
1532                                 case COR_E_REMOTING:
1533                                         return new System.Runtime.Remoting.RemotingException ();
1534                                 case COR_E_SAFEARRAYTYPEMISMATCH:
1535                                         return new SafeArrayTypeMismatchException ();
1536                                 case COR_E_SECURITY:
1537                                         return new SecurityException ();
1538                                 case COR_E_SERIALIZATION:
1539                                         return new System.Runtime.Serialization.SerializationException ();
1540                                 case COR_E_STACKOVERFLOW:
1541                                 case ERROR_STACK_OVERFLOW:
1542                                         return new StackOverflowException ();
1543                                 case COR_E_SYNCHRONIZATIONLOCK:
1544                                         return new SynchronizationLockException ();
1545                                 case COR_E_SYSTEM:
1546                                         return new SystemException ();
1547                                 case COR_E_TARGET:
1548                                         return new TargetException ();
1549                                 case COR_E_TARGETINVOCATION:
1550                                         return new System.Reflection.TargetInvocationException (null);
1551                                 case COR_E_TARGETPARAMCOUNT:
1552                                         return new TargetParameterCountException ();
1553 //                              case COR_E_THREADABORTED:
1554 //                                      ThreadAbortException c'tor is inaccessible
1555 //                                      return new System.Threading.ThreadAbortException ();
1556                                 case COR_E_THREADINTERRUPTED:
1557                                         return new ThreadInterruptedException ();
1558                                 case COR_E_THREADSTATE:
1559                                         return new ThreadStateException ();
1560 //                              case COR_E_THREADSTOP:
1561 //                                      ThreadStopException does not exist
1562 //                                      return new System.Threading.ThreadStopException ();
1563                                 case COR_E_TYPELOAD:
1564                                         return new TypeLoadException ();
1565                                 // MSDN lists COR_E_TYPELOAD twice with different exceptions.
1566                                 // return new EntryPointNotFoundException ();
1567                                 case COR_E_TYPEINITIALIZATION:
1568                                         return new TypeInitializationException("", null);
1569                                 case COR_E_VERIFICATION:
1570                                         return new VerificationException ();
1571 //                              case COR_E_WEAKREFERENCE:
1572 //                                      return new WeakReferenceException ();
1573 //                              case COR_E_VTABLECALLSNOTSUPPORTED:
1574 //                                      return new VTableCallsNotSupportedException ();
1575                         }
1576                         if (errorCode < 0)
1577                                 return new COMException ("", errorCode);
1578                         return null;
1579                 }
1580
1581 #if FEATURE_COMINTEROP
1582                 [DllImport ("oleaut32.dll", CharSet=CharSet.Unicode, EntryPoint = "SetErrorInfo")]
1583                 static extern int _SetErrorInfo (int dwReserved,
1584                         [MarshalAs(UnmanagedType.Interface)] IErrorInfo pIErrorInfo);
1585
1586                 [DllImport ("oleaut32.dll", CharSet=CharSet.Unicode, EntryPoint = "GetErrorInfo")]
1587                 static extern int _GetErrorInfo (int dwReserved,
1588                         [MarshalAs(UnmanagedType.Interface)] out IErrorInfo ppIErrorInfo);
1589
1590                 static bool SetErrorInfoNotAvailable;
1591                 static bool GetErrorInfoNotAvailable;
1592
1593                 internal static int SetErrorInfo (int dwReserved, IErrorInfo errorInfo)
1594                 {
1595                         int retVal = 0;
1596                         errorInfo = null;
1597
1598                         if (SetErrorInfoNotAvailable)
1599                                 return -1;
1600
1601                         try {
1602                                 retVal = _SetErrorInfo (dwReserved, errorInfo);
1603                         }
1604                         catch (Exception) {
1605                                 // ignore any exception - probably there's no suitable SetErrorInfo
1606                                 // method available.
1607                                 SetErrorInfoNotAvailable = true;
1608                         }
1609                         return retVal;
1610                 }
1611
1612                 internal static int GetErrorInfo (int dwReserved, out IErrorInfo errorInfo)
1613                 {
1614                         int retVal = 0;
1615                         errorInfo = null;
1616
1617                         if (GetErrorInfoNotAvailable)
1618                                 return -1;
1619
1620                         try {
1621                                 retVal = _GetErrorInfo (dwReserved, out errorInfo);
1622                         }
1623                         catch (Exception) {
1624                                 // ignore any exception - probably there's no suitable GetErrorInfo
1625                                 // method available.
1626                                 GetErrorInfoNotAvailable = true;
1627                         }
1628                         return retVal;
1629                 }
1630 #endif
1631                 public static Exception GetExceptionForHR (int errorCode)
1632                 {
1633                         return GetExceptionForHR (errorCode, IntPtr.Zero);
1634                 }
1635
1636                 public static Exception GetExceptionForHR (int errorCode, IntPtr errorInfo)
1637                 {
1638 #if FEATURE_COMINTEROP
1639                         IErrorInfo info = null;
1640                         if (errorInfo != (IntPtr)(-1)) {
1641                                 if (errorInfo == IntPtr.Zero) {
1642                                         if (GetErrorInfo (0, out info) != 0) {
1643                                                 info  = null;
1644                                         }
1645                                 } else {
1646                                         info  = Marshal.GetObjectForIUnknown (errorInfo) as IErrorInfo;
1647                                 }
1648                         }
1649
1650                         if (info is ManagedErrorInfo && ((ManagedErrorInfo) info).Exception._HResult == errorCode) {
1651                                 return ((ManagedErrorInfo) info).Exception;
1652                         }
1653
1654                         Exception e = ConvertHrToException (errorCode);
1655                         if (info != null && e != null) {
1656                                 uint helpContext;
1657                                 info.GetHelpContext (out helpContext);
1658                                 string str;
1659                                 info.GetSource (out str);
1660                                 e.Source = str;
1661                                 info.GetDescription (out str);
1662                                 e.SetMessage (str);
1663                                 info.GetHelpFile (out str);
1664
1665                                 if (helpContext == 0) {
1666                                         e.HelpLink = str;
1667                                 } else {
1668                                         e.HelpLink = string.Format ("{0}#{1}", str, helpContext);
1669                                 }
1670                         }
1671                         return e;
1672 #else
1673                         return ConvertHrToException (errorCode);
1674 #endif
1675                 }
1676
1677                 public static int FinalReleaseComObject (object o)
1678                 {
1679                         while (ReleaseComObject (o) != 0);
1680                         return 0;
1681                 }
1682
1683                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1684                 private static extern Delegate GetDelegateForFunctionPointerInternal (IntPtr ptr, Type t);
1685
1686                 public static Delegate GetDelegateForFunctionPointer (IntPtr ptr, Type t)
1687                 {
1688                         if (t == null)
1689                                 throw new ArgumentNullException ("t");
1690                         if (!t.IsSubclassOf (typeof (MulticastDelegate)) || (t == typeof (MulticastDelegate)))
1691                                 throw new ArgumentException ("Type is not a delegate", "t");
1692                         if (t.IsGenericType)
1693                                 throw new ArgumentException ("The specified Type must not be a generic type definition.");
1694                         if (ptr == IntPtr.Zero)
1695                                 throw new ArgumentNullException ("ptr");
1696
1697                         return GetDelegateForFunctionPointerInternal (ptr, t);
1698                 }
1699
1700                 public static TDelegate GetDelegateForFunctionPointer<TDelegate> (IntPtr ptr) {
1701                         return (TDelegate) (object) GetDelegateForFunctionPointer (ptr, typeof (TDelegate));
1702                 }
1703
1704                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1705                 private static extern IntPtr GetFunctionPointerForDelegateInternal (Delegate d);
1706                 
1707                 public static IntPtr GetFunctionPointerForDelegate (Delegate d)
1708                 {
1709                         if (d == null)
1710                                 throw new ArgumentNullException ("d");
1711                         
1712                         return GetFunctionPointerForDelegateInternal (d);
1713                 }
1714
1715                 public static IntPtr GetFunctionPointerForDelegate<TDelegate> (TDelegate d) {
1716                         if (d == null)
1717                                 throw new ArgumentNullException ("d");
1718                         
1719                         return GetFunctionPointerForDelegateInternal ((Delegate)(object)d);
1720                 }
1721
1722                 internal static void SetLastWin32Error (int error)
1723                 {
1724                 }
1725         }
1726 }