我有一个编译成 C 库的 Matlab 函数。我在 C# 应用程序中使用这个库。
如果我第一次在 C 库中调用我的函数,一切正常,但第二次调用会导致异常 - mlfMyfunc 返回空指针 insted 指向结果的指针(output1 和 output2 参数为 IntPtr.Zero,即使在 mlfMyfunc 调用之后也是如此)
我的 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;
}
}
解决方案:
问题是由重复的 Matlab 引擎初始化引起的。每次我调用 Analyze 函数时,引擎都会被初始化(Native.Mcl.mclInitializeApplication
],甚至它在 Native.Mcl.mclTerminateApplication
block 中被正确终止(finally
),重复初始化出现问题。内置的 matlab 函数仍然可以正常工作,但我的库不要。
解决方案正在移动mclInitializeApplication
调用外部 Analyze 函数并确保它在应用程序生命周期内只调用一次。
最佳答案
问题是由重复的 Matlab 引擎初始化引起的。每次我调用 Analyze
函数时,引擎都会被初始化 (Native.Mcl.mclInitializeApplication
),甚至它会被正确终止 (Native.Mcl.mclTerminateApplication
) 在 finally block 中,重复初始化出了问题。内置的 matlab 函数仍然可以正常工作,但我的库不能。
解决方案是将 mclInitializeApplication
调用移到 Analyze
函数之外,并确保它在应用程序生命周期内仅被调用一次。
关于c# - 编译的 Matlab 函数只工作一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5832960/