title: Handling a SAFEARRAY returned from C# server
body: <p>I need to return an array of structure (classes) from a C# library to an unmanaged C++ client. This is the function in the C# library:</p>
  
  <pre><code>[ComVisible(true)]
  [Serializable]
  public sealed class RetrieverProxy : IRetrieverProxy
  {
      public IMyRecord[] RetrieveMyRecords(long[] ids)
      {
          IList&lt;IMyRecord&gt; result = new List&lt;IMyRecord&gt;();
          for (int i = 0; i &lt; ids.Count(); i++)
          {
              result.Add(new MyRecord()
              {
                // some test data
              });
          }
  
          return result.ToArray();
      }
   }
  </code></pre>
  
  <p><code>MyRecord</code> itself contains an array of structures, which are also COM visible and contain a double and a DateTime field.</p>
  
  <p>I get the follow wrapper from regasm:</p>
  
  <pre><code>inline SAFEARRAY * IRetrieverProxy::RetrieveMyRecords (SAFEARRAY * ids) {
      SAFEARRAY * _result = 0;
      HRESULT _hr = raw_RetrieveMyRecords(ids, &amp;_result);
      if (FAILED(_hr)) _com_issue_errorex(_hr, this, __uuidof(this));
      return _result;
  }
  </code></pre>
  
  <p>From the client code, I invoke the library like the following:</p>
  
  <pre><code>SAFEARRAY *pMyRecordsSA;
  SAFEARRAY *pIds;
  // omitting pIds initialization, because from the library I can see 
  // that they are ok
  pMyRecordsSA = pIRetrieverProxy-&gt;RetrieveMyRecords(pIds);
  </code></pre>
  
  <p>The problem I have is how to retrieve the results which are now stored in <code>pMyRecordsSA</code>. I have tried the following but I it's not working:</p>
  
  <pre><code>    IMyRecordPtr pIMyRecords(__uuidof(MyRecord));
      HRESULT hr = SafeArrayAccessData(pMyRecordsSA, (void**)&amp;pIMyRecords);
  </code></pre>
  
  <p>but then trying to use the <code>pIMyRecords</code> pointer gives an access violation (<code>hr</code> is 0K).</p>
  
  <p>Any ideas? I am really stuck on this.</p>