title: COM object IUnknown parameter. InvalidCastException IRowset
body: <p>I write an Ole Db Provider on c# (COM tehnology).</p>
  
  <blockquote>
    <p>Ole Db Provider is .NET DLL.</p>
    
    <p>There is a problem with InvalidCastException: Additional information:
    Unable to cast "MyOleDbProvider.RowsetObject" to type "IRowset".</p>
  </blockquote>
  
  <p>This problem occurs when execution a 'GetRowset' method from <strong>Ole Db Client</strong>.
  In msdn:</p>
  
  <pre><code>HRESULT GetRowset (IUnknown       *pUnkOuter,
                     REFGUID         rguidSchema,
                     ULONG           cRestrictions,
                     const VARIANT   rgRestrictions[],
                     REFIID          riid,
                     ULONG           cPropertySets,
                     DBPROPSET       rgPropertySets[],
                     IUnknown      **ppRowset);
  </code></pre>
  
  <p>I converted the 'GetRowset' such as</p>
  
  <pre><code>[PreserveSig]
  HRESULT GetRowset(
              [In] IntPtr pUnkOuter,
              [In] ref Guid rguidSchema,
              [In] int cRestrictions,
              [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] object[] rgRestrictions,
              [In] ref Guid riid,
              [In] int cProperties,
              [In] IntPtr rgPropertySets,
              [Out, MarshalAs(UnmanagedType.Interface, IidParameterIndex = 4)] out object ppRowset);
  </code></pre>
  
  <p>Implementation:</p>
  
  <pre><code>HRESULT IDBSchemaRowset.GetRowset(IntPtr pUnkOuter, ref Guid rguidSchema, int cRestrictions, object[] rgRestrictions,
              ref Guid riid, int cProperties, IntPtr rgPropertySets, out object ppRowset)
          {
              // not significantly begin
                 ...
              // not significantly end
  
              var rowsetObject = new RowsetObject(rguidSchema);
  
              if (pUnkOuter == IntPtr.Zero)
              {               
                  // always here
                  ppRowset = rowsetObject;
                  return HRESULT.S_OK;
              }
              else
              {                    
                  ppRowset = rowsetObject.AggregateIn(pUnkOuter);
              }
  
              return HRESULT.S_OK;
          }
  </code></pre>
  
  <p>When i pass <strong>ppRowset</strong> InvalidCastException occurs.</p>
  
  <pre><code>public class RowsetObject : IRowset
  {
     ...
  }
  
  [ComImport]
  [Guid("0C733A7C-2A1C-11CE-ADE5-00AA0044773D")]
  [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
  public interface IRowset
  {
      ...
  }
  </code></pre>
  
  <p>This problem occurs only when client is .NET client. The .NET client uses System.Data.OleDb namespace. If client is native client there is no problem.</p>