Merge pull request #489 from alesliehughes/master
[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 !MOONLIGHT
43 using System.Runtime.InteropServices.ComTypes;
44 #endif
45
46 #if !MOONLIGHT
47 using Mono.Interop;
48 #endif
49
50 namespace System.Runtime.InteropServices
51 {
52         public static class Marshal
53         {
54                 /* fields */
55                 public static readonly int SystemMaxDBCSCharSize = 2; // don't know what this is
56                 public static readonly int SystemDefaultCharSize = Environment.OSVersion.Platform == PlatformID.Win32NT ? 2 : 1;
57
58                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
59                 private extern static int AddRefInternal (IntPtr pUnk);
60
61                 public static int AddRef (IntPtr pUnk)
62                 {
63                         if (pUnk == IntPtr.Zero)
64                                 throw new ArgumentException ("Value cannot be null.", "pUnk");
65                         return AddRefInternal (pUnk);
66                 }
67
68                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
69                 public extern static IntPtr AllocCoTaskMem (int cb);
70
71                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
72                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
73                 public extern static IntPtr AllocHGlobal (IntPtr cb);
74
75                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
76                 public static IntPtr AllocHGlobal (int cb)
77                 {
78                         return AllocHGlobal ((IntPtr)cb);
79                 }
80
81                 [MonoTODO]
82                 public static object BindToMoniker (string monikerName)
83                 {
84                         throw new NotImplementedException ();
85                 }
86
87                 [MonoTODO]
88                 public static void ChangeWrapperHandleStrength (object otp, bool fIsWeak)
89                 {
90                         throw new NotImplementedException ();
91                 }
92
93                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
94                 internal extern static void copy_to_unmanaged (Array source, int startIndex,
95                                                                IntPtr destination, int length);
96
97                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
98                 internal extern static void copy_from_unmanaged (IntPtr source, int startIndex,
99                                                                  Array destination, int length);
100
101                 public static void Copy (byte[] source, int startIndex, IntPtr destination, int length)
102                 {
103                         copy_to_unmanaged (source, startIndex, destination, length);
104                 }
105
106                 public static void Copy (char[] source, int startIndex, IntPtr destination, int length)
107                 {
108                         copy_to_unmanaged (source, startIndex, destination, length);
109                 }
110
111                 public static void Copy (short[] source, int startIndex, IntPtr destination, int length)
112                 {
113                         copy_to_unmanaged (source, startIndex, destination, length);
114                 }
115
116                 public static void Copy (int[] source, int startIndex, IntPtr destination, int length)
117                 {
118                         copy_to_unmanaged (source, startIndex, destination, length);
119                 }
120
121                 public static void Copy (long[] source, int startIndex, IntPtr destination, int length)
122                 {
123                         copy_to_unmanaged (source, startIndex, destination, length);
124                 }
125
126                 public static void Copy (float[] source, int startIndex, IntPtr destination, int length)
127                 {
128                         copy_to_unmanaged (source, startIndex, destination, length);
129                 }
130
131                 public static void Copy (double[] source, int startIndex, IntPtr destination, int length)
132                 {
133                         copy_to_unmanaged (source, startIndex, destination, length);
134                 }
135
136                 public static void Copy (IntPtr[] source, int startIndex, IntPtr destination, int length)
137                 {
138                         copy_to_unmanaged (source, startIndex, destination, length);
139                 }
140
141                 public static void Copy (IntPtr source, byte[] destination, int startIndex, int length)
142                 {
143                         copy_from_unmanaged (source, startIndex, destination, length);
144                 }
145
146                 public static void Copy (IntPtr source, char[] destination, int startIndex, int length)
147                 {
148                         copy_from_unmanaged (source, startIndex, destination, length);
149                 }
150
151                 public static void Copy (IntPtr source, short[] destination, int startIndex, int length)
152                 {
153                         copy_from_unmanaged (source, startIndex, destination, length);
154                 }
155
156                 public static void Copy (IntPtr source, int[] destination, int startIndex, int length)
157                 {
158                         copy_from_unmanaged (source, startIndex, destination, length);
159                 }
160
161                 public static void Copy (IntPtr source, long[] destination, int startIndex, int length)
162                 {
163                         copy_from_unmanaged (source, startIndex, destination, length);
164                 }
165
166                 public static void Copy (IntPtr source, float[] destination, int startIndex, int length)
167                 {
168                         copy_from_unmanaged (source, startIndex, destination, length);
169                 }
170
171                 public static void Copy (IntPtr source, double[] destination, int startIndex, int length)
172                 {
173                         copy_from_unmanaged (source, startIndex, destination, length);
174                 }
175
176                 public static void Copy (IntPtr source, IntPtr[] destination, int startIndex, int length)
177                 {
178                         copy_from_unmanaged (source, startIndex, destination, length);
179                 }
180
181                 public static IntPtr CreateAggregatedObject (IntPtr pOuter,
182                                                              object o)
183                 {
184                         throw new NotImplementedException ();
185                 }
186
187 #if !MOONLIGHT
188                 public static object CreateWrapperOfType (object o, Type t)
189                 {
190                         __ComObject co = o as __ComObject;
191                         if (co == null)
192                                 throw new ArgumentException ("o must derive from __ComObject", "o");
193                         if (t == null)
194                                 throw new ArgumentNullException ("t");
195
196                         Type[] itfs = o.GetType ().GetInterfaces ();
197                         foreach (Type itf in itfs) {
198                                 if (itf.IsImport && co.GetInterface (itf) == IntPtr.Zero)
199                                         throw new InvalidCastException ();
200                         }
201
202                         return ComInteropProxy.GetProxy (co.IUnknown, t).GetTransparentProxy ();
203                 }
204 #endif
205
206                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
207                 [ComVisible (true)]
208                 public extern static void DestroyStructure (IntPtr ptr, Type structuretype);
209
210                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
211                 public extern static void FreeBSTR (IntPtr ptr);
212
213                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
214                 public extern static void FreeCoTaskMem (IntPtr ptr);
215
216                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
217                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
218                 public extern static void FreeHGlobal (IntPtr hglobal);
219
220                 static void ClearBSTR (IntPtr ptr)
221                 {
222                         int len = ReadInt32 (ptr, -4);
223
224                         for (int i = 0; i < len; i++)
225                                 WriteByte (ptr, i, 0);
226                 }
227                 
228                 public static void ZeroFreeBSTR (IntPtr s)
229                 {
230                         ClearBSTR (s);
231                         FreeBSTR (s);
232                 }
233
234                 static void ClearAnsi (IntPtr ptr)
235                 {
236                         for (int i = 0; ReadByte (ptr, i) != 0; i++)
237                                 WriteByte (ptr, i, 0);
238                 }
239
240                 static void ClearUnicode (IntPtr ptr)
241                 {
242                         for (int i = 0; ReadInt16 (ptr, i) != 0; i += 2)
243                                 WriteInt16 (ptr, i, 0);
244                 }
245                 
246                 public static void ZeroFreeCoTaskMemAnsi (IntPtr s)
247                 {
248                         ClearAnsi (s);
249                         FreeCoTaskMem (s);
250                 }
251
252                 public static void ZeroFreeCoTaskMemUnicode (IntPtr s)
253                 {
254                         ClearUnicode (s);
255                         FreeCoTaskMem (s);
256                 }
257
258                 public static void ZeroFreeGlobalAllocAnsi (IntPtr s)
259                 {
260                         ClearAnsi (s);
261                         FreeHGlobal (s);
262                 }
263
264                 public static void ZeroFreeGlobalAllocUnicode (IntPtr s)
265                 {
266                         ClearUnicode (s);
267                         FreeHGlobal (s);
268                 }
269
270 #if !MOONLIGHT
271                 public static Guid GenerateGuidForType (Type type)
272                 {
273                         return type.GUID;
274                 }
275
276                 public static string GenerateProgIdForType (Type type)
277                 {
278                         IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (type);
279
280                         foreach (var a in attrs)
281                         {
282                                 var dt = a.Constructor.DeclaringType;
283                                 string name = dt.Name;
284                                 if (name == "ProgIdAttribute")
285                                 {
286                                         var args = a.ConstructorArguments;
287                                         string text = a.ConstructorArguments[0].Value as string;
288                                         if (text == null)
289                                         {
290                                                 text = string.Empty;
291                                         }
292                                         return text;
293                                 }
294                         }
295
296                         return type.FullName;
297                 }
298
299                 [MonoTODO]
300                 public static object GetActiveObject (string progID)
301                 {
302                         throw new NotImplementedException ();
303                 }
304
305                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
306                 private extern static IntPtr GetCCW (object o, Type T);
307
308                 private static IntPtr GetComInterfaceForObjectInternal (object o, Type T)
309                 {
310                         if (IsComObject (o))
311                                 return ((__ComObject)o).GetInterface (T);
312                         else
313                                 return GetCCW (o, T);
314                 }
315
316                 public static IntPtr GetComInterfaceForObject (object o, Type T)
317                 {
318                         IntPtr pItf = GetComInterfaceForObjectInternal (o, T);
319                         AddRef (pItf);
320                         return pItf;
321                 }
322
323                 [MonoTODO]
324                 public static IntPtr GetComInterfaceForObjectInContext (object o, Type t)
325                 {
326                         throw new NotImplementedException ();
327                 }
328
329                 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
330                 public static object GetComObjectData (object obj, object key)
331                 {
332                         throw new NotSupportedException ("MSDN states user code should never need to call this method.");
333                 }
334
335                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
336                 private extern static int GetComSlotForMethodInfoInternal (MemberInfo m);
337
338                 public static int GetComSlotForMethodInfo (MemberInfo m)
339                 {
340                         if (m == null)
341                                 throw new ArgumentNullException ("m");
342                         if (!(m is MethodInfo))
343                                 throw new ArgumentException ("The MemberInfo must be an interface method.", "m");
344                         if (!m.DeclaringType.IsInterface)
345                                 throw new ArgumentException ("The MemberInfo must be an interface method.", "m");
346                         return GetComSlotForMethodInfoInternal (m);
347                 }
348
349                 [MonoTODO]
350                 public static int GetEndComSlot (Type t)
351                 {
352                         throw new NotImplementedException ();
353                 }
354
355                 [MonoTODO]
356                 public static int GetExceptionCode()
357                 {
358                         throw new NotImplementedException ();
359                 }
360
361                 [MonoTODO]
362                 [ComVisible (true)]
363                 public static IntPtr GetExceptionPointers()
364                 {
365                         throw new NotImplementedException ();
366                 }
367
368                 public static IntPtr GetHINSTANCE (Module m)
369                 {
370                         if (m == null)
371                                 throw new ArgumentNullException ("m");
372
373                         return m.GetHINSTANCE ();
374                 }
375 #endif // !NET_2_1
376
377                 [MonoTODO ("SetErrorInfo")]
378                 public static int GetHRForException (Exception e)
379                 {
380                         return e.hresult;
381                 }
382
383                 [MonoTODO]
384                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
385                 public static int GetHRForLastWin32Error()
386                 {
387                         throw new NotImplementedException ();
388                 }
389 #if !MOONLIGHT
390                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
391                 private extern static IntPtr GetIDispatchForObjectInternal (object o);
392
393                 public static IntPtr GetIDispatchForObject (object o)
394                 {
395                         IntPtr pUnk = GetIDispatchForObjectInternal (o);
396                         // Internal method does not AddRef
397                         AddRef (pUnk);
398                         return pUnk;
399                 }
400
401                 [MonoTODO]
402                 public static IntPtr GetIDispatchForObjectInContext (object o)
403                 {
404                         throw new NotImplementedException ();
405                 }
406
407                 [MonoTODO]
408                 public static IntPtr GetITypeInfoForType (Type t)
409                 {
410                         throw new NotImplementedException ();
411                 }
412
413                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
414                 private extern static IntPtr GetIUnknownForObjectInternal (object o);
415
416                 public static IntPtr GetIUnknownForObject (object o)
417                 {
418                         IntPtr pUnk = GetIUnknownForObjectInternal (o);
419                         // Internal method does not AddRef
420                         AddRef (pUnk);
421                         return pUnk;
422                 }
423
424                 [MonoTODO]
425                 public static IntPtr GetIUnknownForObjectInContext (object o)
426                 {
427                         throw new NotImplementedException ();
428                 }
429
430                 [MonoTODO]
431                 [Obsolete ("This method has been deprecated")]
432                 public static IntPtr GetManagedThunkForUnmanagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
433                 {
434                         throw new NotImplementedException ();
435                 }
436
437                 [MonoTODO]
438                 public static MemberInfo GetMethodInfoForComSlot (Type t, int slot, ref ComMemberType memberType)
439                 {
440                         throw new NotImplementedException ();
441                 }
442
443                 public static void GetNativeVariantForObject (object obj, IntPtr pDstNativeVariant)
444                 {
445                         Variant vt = new Variant();
446                         vt.SetValue(obj);
447                         Marshal.StructureToPtr(vt, pDstNativeVariant, false);
448                 }
449
450                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
451                 private static extern object GetObjectForCCW (IntPtr pUnk);
452
453                 public static object GetObjectForIUnknown (IntPtr pUnk)
454                 {
455                         object obj = GetObjectForCCW (pUnk);
456                         // was not a CCW
457                         if (obj == null) {
458                                 ComInteropProxy proxy = ComInteropProxy.GetProxy (pUnk, typeof (__ComObject));
459                                 obj = proxy.GetTransparentProxy ();
460                         }
461                         return obj;
462                 }
463
464                 public static object GetObjectForNativeVariant (IntPtr pSrcNativeVariant)
465                 {
466                         Variant vt = (Variant)Marshal.PtrToStructure(pSrcNativeVariant, typeof(Variant));
467                         return vt.GetValue();
468                 }
469
470                 public static object[] GetObjectsForNativeVariants (IntPtr aSrcNativeVariant, int cVars)
471                 {
472                         if (cVars < 0)
473                                 throw new ArgumentOutOfRangeException ("cVars", "cVars cannot be a negative number.");
474                         object[] objects = new object[cVars];
475                         for (int i = 0; i < cVars; i++)
476                                 objects[i] = GetObjectForNativeVariant ((IntPtr)(aSrcNativeVariant.ToInt64 () +
477                                         i * SizeOf (typeof(Variant))));
478                         return objects;
479                 }
480
481                 [MonoTODO]
482                 public static int GetStartComSlot (Type t)
483                 {
484                         throw new NotImplementedException ();
485                 }
486
487                 [MonoTODO]
488                 [Obsolete ("This method has been deprecated")]
489                 public static Thread GetThreadFromFiberCookie (int cookie)
490                 {
491                         throw new NotImplementedException ();
492                 }
493
494                 public static object GetTypedObjectForIUnknown (IntPtr pUnk, Type t)
495                 {
496                         ComInteropProxy proxy = new ComInteropProxy (pUnk, t);
497                         __ComObject co = (__ComObject)proxy.GetTransparentProxy ();
498                         foreach (Type itf in t.GetInterfaces ()) {
499                                 if ((itf.Attributes & TypeAttributes.Import) == TypeAttributes.Import) {
500                                         if (co.GetInterface (itf) == IntPtr.Zero)
501                                                 return null;
502                                 }
503                         }
504                         return co;
505                 }
506
507                 [MonoTODO]
508                 public static Type GetTypeForITypeInfo (IntPtr piTypeInfo)
509                 {
510                         throw new NotImplementedException ();
511                 }
512
513                 [Obsolete]
514                 [MonoTODO]
515                 public static string GetTypeInfoName (UCOMITypeInfo pTI)
516                 {
517                         throw new NotImplementedException ();
518                 }
519
520                 public static string GetTypeInfoName (ITypeInfo typeInfo)
521                 {
522                         throw new NotImplementedException ();
523                 }
524
525                 [Obsolete]
526                 [MonoTODO]
527                 public static Guid GetTypeLibGuid (UCOMITypeLib pTLB)
528                 {
529                         throw new NotImplementedException ();
530                 }
531
532                 [MonoTODO]
533                 public static Guid GetTypeLibGuid (ITypeLib typelib)
534                 {
535                         throw new NotImplementedException ();
536                 }
537
538                 [MonoTODO]
539                 public static Guid GetTypeLibGuidForAssembly (Assembly asm)
540                 {
541                         throw new NotImplementedException ();
542                 }
543
544                 [Obsolete]
545                 [MonoTODO]
546                 public static int GetTypeLibLcid (UCOMITypeLib pTLB)
547                 {
548                         throw new NotImplementedException ();
549                 }
550
551                 [MonoTODO]
552                 public static int GetTypeLibLcid (ITypeLib typelib)
553                 {
554                         throw new NotImplementedException ();
555                 }
556
557                 [Obsolete]
558                 [MonoTODO]
559                 public static string GetTypeLibName (UCOMITypeLib pTLB)
560                 {
561                         throw new NotImplementedException ();
562                 }
563
564                 [MonoTODO]
565                 public static string GetTypeLibName (ITypeLib typelib)
566                 {
567                         throw new NotImplementedException ();
568                 }
569
570                 [MonoTODO]
571                 public static void GetTypeLibVersionForAssembly (Assembly inputAssembly, out int majorVersion, out int minorVersion)
572                 {
573                         throw new NotImplementedException ();
574                 }
575
576                 public static object GetUniqueObjectForIUnknown (IntPtr unknown)
577                 {
578                         throw new NotImplementedException ();
579                 }
580
581                 [MonoTODO]
582                 [Obsolete ("This method has been deprecated")]
583                 public static IntPtr GetUnmanagedThunkForManagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature)
584                 {
585                         throw new NotImplementedException ();
586                 }
587
588                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
589                 public extern static bool IsComObject (object o);
590
591                 [MonoTODO]
592                 public static bool IsTypeVisibleFromCom (Type t)
593                 {
594                         throw new NotImplementedException ();
595                 }
596
597                 [MonoTODO]
598                 public static int NumParamBytes (MethodInfo m)
599                 {
600                         throw new NotImplementedException ();
601                 }
602 #endif // !NET_2_1
603
604                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
605                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
606                 public static extern int GetLastWin32Error();
607
608                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
609                 public extern static IntPtr OffsetOf (Type t, string fieldName);
610
611                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
612                 public extern static void Prelink (MethodInfo m);
613
614                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
615                 public extern static void PrelinkAll (Type c);
616
617                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
618                 public extern static string PtrToStringAnsi (IntPtr ptr);
619                 
620                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
621                 public extern static string PtrToStringAnsi (IntPtr ptr, int len);
622
623                 public static string PtrToStringAuto (IntPtr ptr)
624                 {
625                         return SystemDefaultCharSize == 2
626                                 ? PtrToStringUni (ptr) : PtrToStringAnsi (ptr);
627                 }
628                 
629                 public static string PtrToStringAuto (IntPtr ptr, int len)
630                 {
631                         return SystemDefaultCharSize == 2
632                                 ? PtrToStringUni (ptr, len) : PtrToStringAnsi (ptr, len);
633                 }
634
635                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
636                 public extern static string PtrToStringUni (IntPtr ptr);
637
638                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
639                 public extern static string PtrToStringUni (IntPtr ptr, int len);
640
641                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
642                 public extern static string PtrToStringBSTR (IntPtr ptr);
643                 
644                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
645                 [ComVisible (true)]
646                 public extern static void PtrToStructure (IntPtr ptr, object structure);
647
648                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
649                 [ComVisible (true)]
650                 public extern static object PtrToStructure (IntPtr ptr, Type structureType);
651
652                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
653                 private extern static int QueryInterfaceInternal (IntPtr pUnk, ref Guid iid, out IntPtr ppv);
654
655                 public static int QueryInterface (IntPtr pUnk, ref Guid iid, out IntPtr ppv)
656                 {
657                         if (pUnk == IntPtr.Zero)
658                                 throw new ArgumentException ("Value cannot be null.", "pUnk");
659                         return QueryInterfaceInternal (pUnk, ref iid, out ppv);
660                 }
661
662                 public static byte ReadByte (IntPtr ptr)
663                 {
664                         return ReadByte (ptr, 0);
665                 }
666
667                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
668                 public extern static byte ReadByte (IntPtr ptr, int ofs);
669
670                 [MonoTODO]
671                 [SuppressUnmanagedCodeSecurity]
672                 public static byte ReadByte ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
673                 {
674                         throw new NotImplementedException ();
675                 }
676
677                 public static short ReadInt16 (IntPtr ptr)
678                 {
679                         return ReadInt16 (ptr, 0);
680                 }
681
682                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
683                 public extern static short ReadInt16 (IntPtr ptr, int ofs);
684
685                 [MonoTODO]
686                 [SuppressUnmanagedCodeSecurity]
687                 public static short ReadInt16 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
688                 {
689                         throw new NotImplementedException ();
690                 }
691
692                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
693                 public static int ReadInt32 (IntPtr ptr)
694                 {
695                         return ReadInt32 (ptr, 0);
696                 }
697
698                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
699                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
700                 public extern static int ReadInt32 (IntPtr ptr, int ofs);
701
702                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
703                 [MonoTODO]
704                 [SuppressUnmanagedCodeSecurity]
705                 public static int ReadInt32 ([In, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
706                 {
707                         throw new NotImplementedException ();
708                 }
709
710                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
711                 public static long ReadInt64 (IntPtr ptr)
712                 {
713                         return ReadInt64 (ptr, 0);
714                 }
715
716                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
717                 public extern static long ReadInt64 (IntPtr ptr, int ofs);
718
719                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
720                 [MonoTODO]
721                 [SuppressUnmanagedCodeSecurity]
722                 public static long ReadInt64 ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
723                 {
724                         throw new NotImplementedException ();
725                 }
726
727                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
728                 public static IntPtr ReadIntPtr (IntPtr ptr)
729                 {
730                         return ReadIntPtr (ptr, 0);
731                 }
732                 
733                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
734                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
735                 public extern static IntPtr ReadIntPtr (IntPtr ptr, int ofs);
736
737                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
738                 [MonoTODO]
739                 public static IntPtr ReadIntPtr ([In, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs)
740                 {
741                         throw new NotImplementedException ();
742                 }
743
744                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
745                 public extern static IntPtr ReAllocCoTaskMem (IntPtr pv, int cb);
746
747                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
748                 public extern static IntPtr ReAllocHGlobal (IntPtr pv, IntPtr cb);
749
750                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
751                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
752                 private extern static int ReleaseInternal (IntPtr pUnk);
753
754                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
755                 public static int Release (IntPtr pUnk)
756                 {
757                         if (pUnk == IntPtr.Zero)
758                                 throw new ArgumentException ("Value cannot be null.", "pUnk");
759                         return ReleaseInternal (pUnk);
760                 }
761
762 #if !MOONLIGHT
763                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
764                 private extern static int ReleaseComObjectInternal (object co);
765
766                 public static int ReleaseComObject (object o)
767                 {
768                         if (o == null)
769                                 throw new ArgumentException ("Value cannot be null.", "o");
770                         if (!IsComObject (o))
771                                 throw new ArgumentException ("Value must be a Com object.", "o");
772                         return ReleaseComObjectInternal (o);
773                 }
774
775                 [Obsolete]
776                 [MonoTODO]
777                 public static void ReleaseThreadCache()
778                 {
779                         throw new NotImplementedException ();
780                 }
781
782                 [MonoNotSupportedAttribute ("MSDN states user code should never need to call this method.")]
783                 public static bool SetComObjectData (object obj, object key, object data)
784                 {
785                         throw new NotSupportedException ("MSDN states user code should never need to call this method.");
786                 }
787 #endif // !NET_2_1
788
789                 [ComVisible (true)]
790                 public static int SizeOf (object structure)
791                 {
792                         return SizeOf (structure.GetType ());
793                 }
794
795                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
796                 public extern static int SizeOf (Type t);
797
798                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
799                 public extern static IntPtr StringToBSTR (string s);
800
801                 //
802                 // I believe this is wrong, because in Mono and in P/Invoke
803                 // we treat "Ansi" conversions as UTF-8 conversions, while
804                 // this one does not do this
805                 //
806                 public static IntPtr StringToCoTaskMemAnsi (string s)
807                 {
808                         int length = s.Length + 1;
809                         IntPtr ctm = AllocCoTaskMem (length);
810
811                         byte[] asBytes = new byte[length];
812                         for (int i = 0; i < s.Length; i++)
813                                 asBytes[i] = (byte)s[i];
814                         asBytes[s.Length] = 0;
815
816                         copy_to_unmanaged (asBytes, 0, ctm, length);
817                         return ctm;
818                 }
819
820                 public static IntPtr StringToCoTaskMemAuto (string s)
821                 {
822                         return SystemDefaultCharSize == 2
823                                 ? StringToCoTaskMemUni (s) : StringToCoTaskMemAnsi (s);
824                 }
825
826                 public static IntPtr StringToCoTaskMemUni (string s)
827                 {
828                         int length = s.Length + 1;
829                         IntPtr ctm = AllocCoTaskMem (length * 2);
830                         
831                         char[] asChars = new char[length];
832                         s.CopyTo (0, asChars, 0, s.Length);
833                         asChars[s.Length] = '\0';
834
835                         copy_to_unmanaged (asChars, 0, ctm, length);
836                         return ctm;
837                 }
838
839                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
840                 public extern static IntPtr StringToHGlobalAnsi (string s);
841
842                 public static IntPtr StringToHGlobalAuto (string s)
843                 {
844                         return SystemDefaultCharSize == 2
845                                 ? StringToHGlobalUni (s) : StringToHGlobalAnsi (s);
846                 }
847
848                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
849                 public extern static IntPtr StringToHGlobalUni (string s);
850
851 #if !MOONLIGHT
852                 public static IntPtr SecureStringToBSTR (SecureString s)
853                 {
854                         if (s == null)
855                                 throw new ArgumentNullException ("s");
856                         int len = s.Length;
857                         IntPtr ctm = AllocCoTaskMem ((len+1) * 2 + 4);
858                         byte [] buffer = null;
859                         WriteInt32 (ctm, 0, len*2);
860                         try {
861                                 buffer = s.GetBuffer ();
862
863                                 for (int i = 0; i < len; i++)
864                                         WriteInt16 (ctm, 4 + (i * 2), (short) ((buffer [(i*2)] << 8) | (buffer [i*2+1])));
865                                 WriteInt16 (ctm, 4 + buffer.Length, 0);
866                         } finally {
867                                 if (buffer != null)
868                                         for (int i = buffer.Length; i > 0; ){
869                                                 i--;
870                                                 buffer [i] = 0;
871                                         }
872                         }
873                         return (IntPtr) ((long)ctm + 4);
874                 }
875
876                 public static IntPtr SecureStringToCoTaskMemAnsi (SecureString s)
877                 {
878                         if (s == null)
879                                 throw new ArgumentNullException ("s");
880                         int len = s.Length;
881                         IntPtr ctm = AllocCoTaskMem (len + 1);
882                         byte [] copy = new byte [len+1];
883
884                         try {
885                                 byte [] buffer = s.GetBuffer ();
886                                 int i = 0, j = 0;
887                                 for (; i < len; i++, j += 2){
888                                         copy [i] = buffer [j+1];
889                                         buffer [j] = 0;
890                                         buffer [j+1] = 0;
891                                 }
892                                 copy [i] = 0;
893                                 copy_to_unmanaged (copy, 0, ctm, len+1);
894                         } finally {
895                                 // Ensure that we clear the buffer.
896                                 for (int i = len; i > 0; ){
897                                         i--;
898                                         copy [i] = 0;
899                                 }
900                         }
901                         return ctm;
902                 }
903
904                 public static IntPtr SecureStringToCoTaskMemUnicode (SecureString s)
905                 {
906                         if (s == null)
907                                 throw new ArgumentNullException ("s");
908                         int len = s.Length;
909                         IntPtr ctm = AllocCoTaskMem (len * 2 + 2);
910                         byte [] buffer = null;
911                         try {
912                                 buffer = s.GetBuffer ();
913                                 for (int i = 0; i < len; i++)
914                                         WriteInt16 (ctm, i * 2, (short) ((buffer [(i*2)] << 8) | (buffer [i*2+1])));
915                                 WriteInt16 (ctm, buffer.Length, 0);
916                         } finally {
917                                 if (buffer != null)
918                                         for (int i = buffer.Length; i > 0; ){
919                                                 i--;
920                                                 buffer [i] = 0;
921                                         }
922                         }
923                         return ctm;
924                 }
925
926                 public static IntPtr SecureStringToGlobalAllocAnsi (SecureString s)
927                 {
928                         if (s == null)
929                                 throw new ArgumentNullException ("s");
930                         return SecureStringToCoTaskMemAnsi (s);
931                 }
932
933                 public static IntPtr SecureStringToGlobalAllocUnicode (SecureString s)
934                 {
935                         if (s == null)
936                                 throw new ArgumentNullException ("s");
937                         return SecureStringToCoTaskMemUnicode (s);
938                 }
939 #endif
940
941                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
942                 [ComVisible (true)]
943                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
944                 public extern static void StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld);
945
946                 public static void ThrowExceptionForHR (int errorCode) {
947                         Exception ex = GetExceptionForHR (errorCode);
948                         if (ex != null)
949                                 throw ex;
950                 }
951
952                 public static void ThrowExceptionForHR (int errorCode, IntPtr errorInfo) {
953                         Exception ex = GetExceptionForHR (errorCode, errorInfo);
954                         if (ex != null)
955                                 throw ex;
956                 }
957
958                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
959                 public extern static IntPtr UnsafeAddrOfPinnedArrayElement (Array arr, int index);
960
961                 public static void WriteByte (IntPtr ptr, byte val)
962                 {
963                         WriteByte (ptr, 0, val);
964                 }
965
966                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
967                 public extern static void WriteByte (IntPtr ptr, int ofs, byte val);
968
969                 [MonoTODO]
970                 [SuppressUnmanagedCodeSecurity]
971                 public static void WriteByte ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, byte val)
972                 {
973                         throw new NotImplementedException ();
974                 }
975
976                 public static void WriteInt16 (IntPtr ptr, short val)
977                 {
978                         WriteInt16 (ptr, 0, val);
979                 }
980
981                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
982                 public extern static void WriteInt16 (IntPtr ptr, int ofs, short val);
983
984                 [MonoTODO]
985                 [SuppressUnmanagedCodeSecurity]
986                 public static void WriteInt16 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, short val)
987                 {
988                         throw new NotImplementedException ();
989                 }
990
991                 public static void WriteInt16 (IntPtr ptr, char val)
992                 {
993                         WriteInt16 (ptr, 0, val);
994                 }
995
996                 [MonoTODO]
997                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
998                 public extern static void WriteInt16 (IntPtr ptr, int ofs, char val);
999
1000                 [MonoTODO]
1001                 public static void WriteInt16([In, Out] object ptr, int ofs, char val)
1002                 {
1003                         throw new NotImplementedException ();
1004                 }
1005
1006                 public static void WriteInt32 (IntPtr ptr, int val)
1007                 {
1008                         WriteInt32 (ptr, 0, val);
1009                 }
1010
1011                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1012                 public extern static void WriteInt32 (IntPtr ptr, int ofs, int val);
1013
1014                 [MonoTODO]
1015                 [SuppressUnmanagedCodeSecurity]
1016                 public static void WriteInt32([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, int val)
1017                 {
1018                         throw new NotImplementedException ();
1019                 }
1020
1021                 public static void WriteInt64 (IntPtr ptr, long val)
1022                 {
1023                         WriteInt64 (ptr, 0, val);
1024                 }
1025
1026                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1027                 public extern static void WriteInt64 (IntPtr ptr, int ofs, long val);
1028
1029                 [MonoTODO]
1030                 [SuppressUnmanagedCodeSecurity]
1031                 public static void WriteInt64 ([In, Out, MarshalAs (UnmanagedType.AsAny)] object ptr, int ofs, long val)
1032                 {
1033                         throw new NotImplementedException ();
1034                 }
1035
1036                 public static void WriteIntPtr (IntPtr ptr, IntPtr val)
1037                 {
1038                         WriteIntPtr (ptr, 0, val);
1039                 }
1040
1041                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1042                 public extern static void WriteIntPtr (IntPtr ptr, int ofs, IntPtr val);
1043
1044                 [MonoTODO]
1045                 public static void WriteIntPtr([In, Out, MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs, IntPtr val)
1046                 {
1047                         throw new NotImplementedException ();
1048                 }
1049
1050                 public static Exception GetExceptionForHR (int errorCode) {
1051                         return GetExceptionForHR (errorCode, IntPtr.Zero);
1052                 }
1053
1054                 public static Exception GetExceptionForHR (int errorCode, IntPtr errorInfo) {
1055
1056                         const int E_OUTOFMEMORY = unchecked ((int)0x8007000EL);
1057                         const int E_INVALIDARG = unchecked ((int)0X80070057);
1058                         
1059                         switch (errorCode)
1060                         {
1061                         case E_OUTOFMEMORY:
1062                                 return new OutOfMemoryException ();
1063                         case E_INVALIDARG:
1064                                 return new ArgumentException ();
1065                         }
1066                         if (errorCode < 0)
1067                                 return new COMException ("", errorCode);
1068                         return null;
1069                 }
1070
1071 #if !MOONLIGHT
1072                 public static int FinalReleaseComObject (object o)
1073                 {
1074                         while (ReleaseComObject (o) != 0);
1075                         return 0;
1076                 }
1077 #endif
1078
1079                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1080                 private static extern Delegate GetDelegateForFunctionPointerInternal (IntPtr ptr, Type t);
1081
1082                 public static Delegate GetDelegateForFunctionPointer (IntPtr ptr, Type t)
1083                 {
1084                         if (t == null)
1085                                 throw new ArgumentNullException ("t");
1086                         if (!t.IsSubclassOf (typeof (MulticastDelegate)) || (t == typeof (MulticastDelegate)))
1087                                 throw new ArgumentException ("Type is not a delegate", "t");
1088                         if (t.IsGenericType)
1089                                 throw new ArgumentException ("The specified Type must not be a generic type definition.");
1090                         if (ptr == IntPtr.Zero)
1091                                 throw new ArgumentNullException ("ptr");
1092
1093                         return GetDelegateForFunctionPointerInternal (ptr, t);
1094                 }
1095
1096                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1097                 private static extern IntPtr GetFunctionPointerForDelegateInternal (Delegate d);
1098                 
1099                 public static IntPtr GetFunctionPointerForDelegate (Delegate d)
1100                 {
1101                         if (d == null)
1102                                 throw new ArgumentNullException ("d");
1103                         
1104                         return GetFunctionPointerForDelegateInternal (d);
1105                 }
1106         }
1107 }