似乎无法多次调用matlab:
[STAThread]
static void Main(string[] args)
{
IList<DTO> LotsOfWork = new List<DTO>();
// create some work
for(int c = 0; c < 10; c++)
{
LotsOfWork.Add(new DTO(){ Id = c, Parameter1 = c, Parameter2 = c });
}
// deal with work
foreach (DTO DTO in LotsOfWork)
{
MLApp.MLApp matlab = new MLApp.MLApp();
object result;
matlab.Execute("clear;");
matlab.PutWorkspaceData("a", "base", DTO.Parameter1);
matlab.PutWorkspaceData("b", "base", DTO.Parameter2);
matlab.Execute("result = a + b;");
matlab.GetWorkspaceData("result", "base", out result);
}
}
public class DTO
{
public int Id { get; set; }
public double Parameter1 { get; set; }
public double Parameter2 { get; set; }
public string Result { get; set; }
}
第二次循环迭代抛出异常:
at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData)
at MLApp.DIMLApp.GetWorkspaceData(String Name, String Workspace, Object& pdata)
at Sandbox.Program.Main(String[] args) in C:\Bla\Program.cs:line 53
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
我也想知道是否可以运行类似'threaded'的东西(即为每个DTO对象生成一个线程)。感谢。
答案 0 :(得分:2)
解。替换:
object result;
使用:
object result = null;
这是Mathworks的回复:
这个错误是由于GetWorkspaceData期望一个空的VARIANT作为输出参数但在运行一次循环之后,结果实际上变为值为0.0的double。因此,您需要将循环更改为:
foreach (DTO DTO in LotsOfWork)
{
object result = null; //Initialize as null
matlab.Execute("clear;");
matlab.PutWorkspaceData("a", "base", DTO.Parameter1);
matlab.PutWorkspaceData("b", "base", DTO.Parameter2);
matlab.Execute("result = a + b;");
matlab.GetWorkspaceData("result", "base", out result);
}