我有一个非常简单的matlab函数:
function [x,y] = myfunc(a,b,myStruct)
x = a + b + myStruct.score;
y = sprintf('Hello %s',myStruct.name);
然后我尝试通过执行以下操作从c#中调用它:
class Program
{
static void Main(string[] args)
{
MLApp.MLApp matlab = new MLApp.MLApp();
matlab.Execute(@"c:\matlab");
object result = null;
var student= new Student {grade = "A", name = "StudentName", score = 90};
matlab.Feval("myfunc", 2, out result, 3.14, 42.0, student);
var res = result as object[];
}
public struct Student
{
public string name;
private string gr;
private int sc;
public string grade
{
get { return gr; }
set { gr = value; }
}
public int score
{
get { return sc; }
set { sc = value; }
}
}
}
不幸的是,这总会导致:
mscorlib.dll中发生了未处理的“System.ArgumentException”类型异常 附加信息:价值不在预期范围内。
任何人都有任何想法我错过了什么?我遵循了matlab文档,基本上说,只要你有一个可公开访问的字段,那么你就好了。
堆栈跟踪:
at System.RuntimeType.InvokeDispMethod(String name,BindingFlags invokeAttr,Object target,Object [] args,Boolean [] byrefModifiers,Int32 culture,String [] namedParameters) at System.RuntimeType.InvokeMember(String name,BindingFlags bindingFlags,Binder binder,Object target,Object [] providedArgs,ParameterModifier [] modifiers,CultureInfo culture,String [] namedParams) at System.RuntimeType.ForwardCallToInvokeMember(String memberName,BindingFlags flags,Object target,Int32 [] aWrapperTypes,MessageData& msgData) 在MLApp.DIMLApp.Feval(String bstrName,Int32 nargout,Object& pvarArgOut,Object arg1,Object arg2,Object arg3,Object arg4,Object arg5,Object arg6,Object arg7,Object arg8,Object arg9,Object arg10,Object arg11, Object arg12,Object arg13,Object arg14,Object arg15,Object arg16,Object arg17,Object arg18,Object arg19,Object arg20,Object arg21,Object arg22,Object arg23,Object arg24,Object arg25,Object arg26,Object arg27,Object arg28 ,Object arg29,Object arg30,Object arg31,Object arg32) at rmtest.Program.Main(String [] args)在C:\ Users {username} \ documents \ visual studio 2015 \ Projects \ rmtest \ rmtest \ Program.cs:第20行 在System.AppDomain._nExecuteAssembly(RuntimeAssembly程序集,String [] args) 在System.AppDomain.ExecuteAssembly(String assemblyFile,Evidence assemblySecurity,String [] args) 在Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() 在System.Threading.ThreadHelper.ThreadStart_Context(对象状态) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean preserveSyncCtx) 在System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback回调,对象状态) 在System.Threading.ThreadHelper.ThreadStart()
答案 0 :(得分:0)
这就是诀窍:
IntPtr pnt = Marshal.AllocHGlobal(Marshal.SizeOf(student));
matlab.Feval("myfunc", 2, out result, 3.14, 42.0, pnt);