title: Calling Matlab's MLApp.MLAppClass.FEval from F#
body: <p>Matlab provides a COM interface that supports remote execution of arbitrary functions (and code snippets). In particular, it has an Feval method that calls a given Matlab function. The third parameter to this method, pvarArgOut, has COM type VARIANT*, and appears in the Visual Studio F# editor as an argument of type:</p>
  
  <pre><code>pvarArgOut: byref&lt;obj&gt;
  </code></pre>
  
  <p>The following code calls interp1, which in Matlab returns a matrix (i.e. 2D double array) result, as is normal for most Matlab functions.</p>
  
  <pre><code>let matlab = new MLApp.MLAppClass()
  
  let vector_to_array2d (v : vector) = Array2D.init v.Length 1 (fun i j -&gt; v.[i])
  
  let interp1 (xs : vector) (ys : vector) (xi : vector) =
      let yi : obj = new obj()
      matlab.Feval("interp1", 1, ref yi, vector_to_array2d xs, vector_to_array2d ys, vector_to_array2d xi)
      yi :?&gt; float[,]
  </code></pre>
  
  <p>This code compiles fine, but when calling interp1, I get a COM exception:</p>
  
  <pre><code>A first chance exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
  A first chance exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll
  An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll
  
  Additional information: Invalid callee. (Exception from HRESULT: 0x80020010 (DISP_E_BADCALLEE))
  </code></pre>
  
  <p>I get the same error whether initialize yi with a new obj, a new Array2D, or null.</p>
  
  <p>How does F# translate VARIANT output arguments?</p>
  
  <p><em>Update</em></p>
  
  <p>Here is the corrected version:</p>
  
  <pre><code>let matlab = new MLApp.MLAppClass()
  
  let vector_to_array2d (v : vector) = Array2D.init v.Length 1 (fun i j -&gt; v.[i])
  
  let interp1 (xs : vector) (ys : vector) (xi : vector) =
      let mutable oi : obj = null
      matlab.Feval("interp1", 1, &amp;oi, vector_to_array2d xs, vector_to_array2d ys, vector_to_array2d xi)
      (oi :?&gt; obj[]).[0] :?&gt; float[,]
  </code></pre>