Merge pull request #167 from konrad-kruczynski/send_async_fix
[mono.git] / mcs / class / corlib / System / __ComObject.cs
1 //
2 // System.__ComObject
3 //
4 // Authors:
5 //   Sebastien Pouliot <sebastien@ximian.com>
6 //   Kornél Pál <http://www.kornelpal.hu/>
7 //   Jonathan Chambers <joncham@gmail.com>
8 //
9 // Copyright (C) 2004 Novell (http://www.novell.com)
10 // Copyright (C) 2005 Kornél Pál
11 // Copyright (C) 2006 Jonathan Chambers
12 //
13
14 //
15 // Permission is hereby granted, free of charge, to any person obtaining
16 // a copy of this software and associated documentation files (the
17 // "Software"), to deal in the Software without restriction, including
18 // without limitation the rights to use, copy, modify, merge, publish,
19 // distribute, sublicense, and/or sell copies of the Software, and to
20 // permit persons to whom the Software is furnished to do so, subject to
21 // the following conditions:
22 //
23 // The above copyright notice and this permission notice shall be
24 // included in all copies or substantial portions of the Software.
25 //
26 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
29 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
30 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
31 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
32 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 //
34
35 using Mono.Interop;
36 using System.Collections;
37 using System.Runtime.InteropServices;
38 using System.Runtime.CompilerServices;
39 using System.Threading;
40
41 namespace System
42 {
43         // This is a private class that is used as a generic wrapper class
44         // for COM objects that have no specific wrapper class.
45         //
46         // It has no public methods, it's functionality is exposed trough
47         // System.Runtime.InteropServices.Marshal class and can be casted to
48         // any interface that is implemented by the wrapped COM object.
49         //
50         // This class is referenced in .NET Framework SDK Documentation so
51         // many times that obj.GetType().FullName == "System.__ComObject" and
52         // Type.GetType("System.__ComObject") may be used.
53
54         internal class __ComObject : MarshalByRefObject
55         {
56 #pragma warning disable 169     
57                 #region Sync with object-internals.h
58                 IntPtr iunknown;
59                 IntPtr hash_table;
60                 SynchronizationContext synchronization_context;
61                 #endregion
62 #pragma warning restore 169
63
64                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
65                 internal static extern __ComObject CreateRCW (Type t);
66
67                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
68                 private extern void ReleaseInterfaces ();
69
70                 ~__ComObject ()
71                 {       
72                         if (synchronization_context != null)
73                                 synchronization_context.Post ((state) => ReleaseInterfaces (), this);
74                         else
75                                 ReleaseInterfaces ();                           
76                 }
77
78                 public __ComObject ()
79                 {
80                         Initialize (GetType ());
81                 }
82
83                 internal __ComObject (Type t) {
84                         Initialize (t);
85                 }
86
87                 internal __ComObject (IntPtr pItf)
88                 {
89                         InitializeApartmentDetails ();
90                         Guid iid = IID_IUnknown;
91                         int hr = Marshal.QueryInterface (pItf, ref iid, out iunknown);
92                         Marshal.ThrowExceptionForHR (hr);
93                 }
94
95                 internal void Initialize (Type t)
96                 {
97                         InitializeApartmentDetails ();
98                         // Guard multiple invocation.
99                         if (iunknown != IntPtr.Zero)
100                                 return;
101                         
102                         ObjectCreationDelegate ocd = ExtensibleClassFactory.GetObjectCreationCallback (t);
103                         if (ocd != null) {
104                                 iunknown = ocd (IntPtr.Zero);
105                                 if (iunknown == IntPtr.Zero)
106                                         throw new COMException (string.Format("ObjectCreationDelegate for type {0} failed to return a valid COM object", t));
107                         }
108                         else {
109                                 int hr = CoCreateInstance (GetCLSID (t), IntPtr.Zero, 0x1 | 0x4 | 0x10, IID_IUnknown, out iunknown);
110                                 Marshal.ThrowExceptionForHR (hr);
111                         }
112                 }
113
114                 private void InitializeApartmentDetails ()
115                 {
116                         // Only synchronization_context if thread is STA.
117                         if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA)
118                                 return;
119                         
120                         synchronization_context = SynchronizationContext.Current;
121
122                         // Check whether the current context is a plain SynchronizationContext object
123                         // and handle this as if no context was set at all.
124                         if (synchronization_context != null &&
125                                 synchronization_context.GetType () == typeof(SynchronizationContext))
126                                 synchronization_context = null;                 
127                 }
128
129                 private static Guid GetCLSID (Type t)
130                 {
131                         if (t.IsImport)
132                                 return t.GUID;
133
134                         // look at supertypes
135                         Type super = t.BaseType;
136                         while (super != typeof (object)) {
137                                 if (super.IsImport)
138                                         return super.GUID;
139                                 super = super.BaseType;
140                         }
141                         throw new COMException ("Could not find base COM type for type " + t.ToString());
142                 }
143
144                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
145                 internal extern IntPtr GetInterfaceInternal (Type t, bool throwException);
146
147                 internal IntPtr GetInterface (Type t, bool throwException) {
148                         CheckIUnknown ();
149                         return GetInterfaceInternal (t, throwException);
150                 }
151
152                 internal IntPtr GetInterface(Type t)
153                 {
154                         return GetInterface (t, true);
155                 }
156
157                 private void CheckIUnknown ()
158                 {
159                         if (iunknown == IntPtr.Zero)
160                                 throw new InvalidComObjectException ("COM object that has been separated from its underlying RCW cannot be used.");
161                 }
162
163                 internal IntPtr IUnknown
164                 {
165                         get
166                         {
167                                 if (iunknown == IntPtr.Zero)
168                                         throw new InvalidComObjectException ("COM object that has been separated from its underlying RCW cannot be used.");
169                                 return iunknown;
170                         }
171                 }
172
173                 internal IntPtr IDispatch
174                 {
175                         get
176                         {
177                                 IntPtr pUnk = GetInterface (typeof (IDispatch));
178                                 if (pUnk == IntPtr.Zero)
179                                         throw new InvalidComObjectException ("COM object that has been separated from its underlying RCW cannot be used.");
180                                 return pUnk;
181                         }
182                 }
183
184                 internal static Guid IID_IUnknown
185                 {
186                         get
187                         {
188                                 return new Guid("00000000-0000-0000-C000-000000000046");
189                         }
190                 }
191
192                 internal static Guid IID_IDispatch
193                 {
194                         get
195                         {
196                                 return new Guid ("00020400-0000-0000-C000-000000000046");
197                         }
198                 }
199
200                 public override bool Equals (object obj)
201                 {
202                         CheckIUnknown ();
203                         if (obj == null)
204                                 return false;
205
206                         __ComObject co = obj as __ComObject;
207                         if ((object)co == null)
208                                 return false;
209                         return (iunknown == co.IUnknown);
210                 }
211
212                 public override int GetHashCode ()
213                 {
214                         CheckIUnknown ();
215                         // not what MS seems to do, 
216                         // but IUnknown is identity in COM
217                         return iunknown.ToInt32 ();
218                 }
219
220                 [DllImport ("ole32.dll", CallingConvention = CallingConvention.StdCall, ExactSpelling = true, PreserveSig = true)]
221                 static extern int CoCreateInstance (
222                    [In, MarshalAs (UnmanagedType.LPStruct)] Guid rclsid,
223                    IntPtr pUnkOuter,
224                    uint dwClsContext,
225                   [In, MarshalAs (UnmanagedType.LPStruct)] Guid riid,
226                         out IntPtr pUnk);
227         }
228 }