title: Passing a Safearray of custom types from C++ to C#
body: <p>how can one use a <code>Safearray</code> to pass an array of custom types (a class containing only properties) from C++ to C#? Is using the <code>VT_RECORD</code> type the right way to do it?</p>
  
  <p>I am trying in the following way, but <strike><code>SafeArrayPutElement</code> returns an error when trying to fill the safearray</strike> the reference to the array of classes gets to the managed code as a NULL.</p>
  
  <p>I have something like the following in the managed world:</p>
  
  <pre><code>[ComVisible(true)]
  public interface IStatistics
  {
      double Mean { get; set; } 
      double StdDev { get; set; } 
  }
  
  [Serializable]
  [ComVisible(true)]
  public class Statistics : IStatistics
  {
      public Mean { get; set; }
      public double StdDev { get; set; } 
  }
  </code></pre>
  
  <p>Unmanaged world:</p>
  
  <pre><code>HRESULT hr = CoInitialize(NULL);
  ...
  SAFEARRAY *pEquationsStatistics;
  
  // common dimensions for all arrays
  SAFEARRAYBOUND dimensions[1];  
  dimensions[0].cElements = 2;   
  dimensions[0].lLbound = 0;    
  
  pEquationsStatistics = SafeArrayCreate(VT_RECORD, 1, dimensions);
  ...
  
  for (long i = 0; i &lt; dimensions[0].cElements; i++)
  {
      long indices[1];
      indices[0] = 0;
  
      ... 
  
      // Equation statistics
      IStatisticsPtr pIStatistics(__uuidof(Statistics)); 
      pIStatistics-&gt;PutMean(1.0); // so far so good
  
      result = SafeArrayPutElement(pEquationsStatistics, indices, pIStatistics);
  
      ...
      indices[0]++;
  }
  </code></pre>
  
  <p>Please note that the I am able use the <code>SafeArray</code> to pass other arrays of <code>BSTR</code> with no problems between the two applications. So this is something peculiar to passing a structure.</p>
  
  <p>Stefano   </p>