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