问题
I have a Matlab function compiled into C library. I am using this library from C# application.
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)
My DoubleArray
class (wrapper around mx...
functions), is well tested and I think it works correctly.
Do you have any idea where problem could be?
Thanks. Lukas
C# 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<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;
}
}
Solution:
The problem was caused by repetitionary Matlab engine initialization. Each time I call Analyze function the engine gets initialized (Native.Mcl.mclInitializeApplication
] and even it's being properly terminated (Native.Mcl.mclTerminateApplication
) in finally
block, something goes wrong with repetitionary initialization. Built in matlab functions still works properly, but my library don't.
The solution is moving mclInitializeApplication
call outside Analyze function and ensuring it's called only once in application lifetime.
回答1:
The problem was caused by repetitionary Matlab engine initialization. Each time I call Analyze
function the engine gets initialized (Native.Mcl.mclInitializeApplication
) and even it's being properly terminated (Native.Mcl.mclTerminateApplication
) in finally block, something goes wrong with repetitionary initialization. Built in matlab functions still works properly, but my library don't.
The solution is moving mclInitializeApplication
call outside Analyze
function and ensuring it's called only once in application lifetime.
回答2:
try to allocate IntPtrs using globalAlloc
来源:https://stackoverflow.com/questions/5832960/compiled-matlab-function-works-only-once