2011-04-29 14 views
2

我有一個Matlab函數編譯成C庫。我正在使用C#應用程序的這個庫。編譯的Matlab函數只能工作一次

如果我第一次在C庫中調用我的函數,一切正常,但第二次調用導致一個異常 - mlfMyfunc返回空指針insted指向結果(即使在mlfMyfunc調用之後,output1和output2參數也是IntPtr.Zero )

我的DoubleArray類(包裝mx...功能),已經過很好的測試,我認爲它能正常工作。

你有什麼想法可以解決問題嗎?

謝謝。盧卡斯

C#代碼:

using Native; 

class MatlabAlgosBridge { 
    [DllImport("Algos.dll"] 
    private static extern bool AlgosInitialize(); 

    [DllImport("Algos.dll")] 
    private static extern void AlgosTerminate(); 

    [DllImport("Algos.dll")] 
    private static extern bool mlfMyfunc([In] int nargout, ref IntPtr output1, ref IntPtr output2, [In] IntPtr xVar, [In] IntPtr time, [In] IntPtr algoParam, [In] IntPtr Ts, [In] IntPtr codes); 

    public List<double> Analyze(List<double> xValues) { 
    double[] result = null; 
    try { 
     Native.Mcl.mclInitializeApplication("NULL", 0) 
     AlgosInitialize(); 

     DoubleArray xValM = DoubleArray.CreateMatrix(xValues.Data.Count, 1); 
     // Other parameter initialization 

     IntPtr output1 = IntPtr.Zero; 
     IntPtr output2 = IntPtr.Zero; 

     mlfMyfunc(2, ref output1, ref output2, xValM.Pointer, time.Pointer, params.Pointer, ts.Pointer, codes.Pointer); 

     result = new MArray(output1).AsDoubleVector(); 
    } 
    finally { 
     AlgosTerminate(); 
     Native.Mcl.mclTerminateApplication(); 
    } 

    return result; 
    } 
} 

解決方案:

問題是由repetitionary Matlab引擎初始化所致。每次我調用Analyze函數時,引擎初始化(Native.Mcl.mclInitializeApplication),甚至在finally區塊中正確終止(Native.Mcl.mclTerminateApplication),但重複初始化會出現問題。內置matlab函數仍然正常工作,但是我的庫不能正常工作。

該解決方案是移動mclInitializeApplication外呼分析功能,並確保它被稱爲只有一次在應用程序生命週期。

回答

2

分配IntPtrs問題是由repetitionary Matlab引擎初始化引起的。每次我打電話Analyze函數引擎初始化(Native.Mcl.mclInitializeApplication),甚至在終止塊中正確終止(Native.Mcl.mclTerminateApplication),重複初始化會出現問題。內置的matlab功能仍然正常工作,但我的圖書館沒有。

解決方案正在移動mclInitializeApplication呼叫Analyze以外的函數,並確保它在應用程序生命週期中僅調用一次。

0

嘗試使用的GlobalAlloc

+0

謝謝您的建議,但它沒有奏效。問題在於Matlab引擎初始化 - 請參閱我編輯的問題 – 2011-05-04 19:56:48