Matlab提供了一個支持遠程執行任意函數(和代碼片段)的COM接口。特別是,它有一個調用給定Matlab函數的Feval方法。該方法,pvarArgOut,第三參數具有COM類型VARIANT *,和在Visual Studio F#編輯顯示爲類型的參數:調用MATLAB的MLApp.MLAppClass.FEval來自F#
pvarArgOut: byref<obj>
下面的代碼調用interp1,其在Matlab返回一個矩陣(即2D雙數組)結果,正如大多數Matlab函數一樣。
let matlab = new MLApp.MLAppClass()
let vector_to_array2d (v : vector) = Array2D.init v.Length 1 (fun i j -> 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 :?> float[,]
此代碼編譯罰款,但調用interp1的時候,我得到一個COM異常:
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))
我得到同樣的錯誤是否與新的OBJ,新Array2D,或空初始化義。
F#如何翻譯VARIANT輸出參數?
更新
這裏是修正版本:從F#V1.1.5和F#PowerPack中的StrangeLights.com
let matlab = new MLApp.MLAppClass()
let vector_to_array2d (v : vector) = Array2D.init v.Length 1 (fun i j -> v.[i])
let interp1 (xs : vector) (ys : vector) (xi : vector) =
let mutable oi : obj = null
matlab.Feval("interp1", 1, &oi, vector_to_array2d xs, vector_to_array2d ys, vector_to_array2d xi)
(oi :?> obj[]).[0] :?> float[,]
這個工程! - 將yi初始化爲null而不是新的obj()。調用之後,yi變量包含一個對象數組,其中第一個元素設置爲一個2維雙精度數組。完善。感謝Brian! – Matthew 2010-05-13 23:09:31
嗨馬修,請你補充完整的工作例子嗎?提前致謝。 – 2010-05-15 08:52:35