title: Compiled Matlab function works only once
body: <p>I have a Matlab function compiled into C library. I am using this library from C# application.</p>
  
  <p>If I call my function in C library for the first time, everything works fine, but the second call causes an exception - mlfMyfunc returns null pointer insted pointer to results (output1 and output2 parameters are IntPtr.Zero even after mlfMyfunc call)</p>
  
  <p>My <code>DoubleArray</code> class (wrapper around <code>mx...</code> functions), is well tested and I think it works correctly.</p>
  
  <p>Do you have any idea where problem could be?</p>
  
  <p>Thanks. Lukas</p>
  
  <p>C# code:</p>
  
  <pre><code>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&lt;double&gt; Analyze(List&lt;double&gt; 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;
     }
  }
  </code></pre>
  
  <p><strong>Solution:</strong></p>
  
  <p>The problem was caused by repetitionary Matlab engine initialization. Each time I call Analyze function the engine gets initialized (<code>Native.Mcl.mclInitializeApplication</code>] and even it's being properly terminated (<code>Native.Mcl.mclTerminateApplication</code>) in <code>finally</code> block, something goes wrong with repetitionary initialization. Built in matlab functions still works properly, but my library don't.</p>
  
  <p>The solution is moving <code>mclInitializeApplication</code> call outside Analyze function and ensuring it's called only once in application lifetime.</p>