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