2010-05-13 77 views
1

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[,] 

回答

1

你不想ref yi,你想

let mutable yi = new obj() 
thatfunc(..., &yi, ...) 

雖然我認爲那不會解決它。有沒有一個調用這個特定API的C#示例?

+0

這個工程! - 將yi初始化爲null而不是新的obj()。調用之後,yi變量包含一個對象數組,其中第一個元素設置爲一個2維雙精度數組。完善。感謝Brian! – Matthew 2010-05-13 23:09:31

+0

嗨馬修,請你補充完整的工作例子嗎?提前致謝。 – 2010-05-15 08:52:35

1

文章F Sharp And MATLAB介紹如何使用MATLAB。

缺少的步驟是通過創建一個互通的dll TLBIMP如

TLBIMP 「C:\ Program Files文件\ MATLAB \ R2006a \ BIN \ WIN32 \ mlapp.tlb」

那麼F#導入此DLL中與

'r組成 「Interop.MLApp.dll」'

+0

謝謝馬特;我看過這篇文章 - 這是一篇很好的文章,它讓我開始了,但它不包括使用Feval。我已經創建了互操作性DLL並將其添加爲項目引用,所以不能這麼做... – Matthew 2010-05-13 07:53:02

+0

糟糕,因爲認爲它很簡單。我只是快速瀏覽並重現行爲,但沒有更接近解決方案。 – 2010-05-13 10:42:29