在C#中使用MLapp时“无效的Calle”

时间:2014-01-14 16:32:29

标签: c# matlab com com-interop matlab-deployment

使用MLApp.GetWorkspaceData功能时我遇到了一些奇怪的问题。我注意到如果我执行以下操作,此功能将正常工作:

matlab = new MLApp.MLAppClass();

object myObject;

matlab.GetWorkspaceData("myVariable", "base", out myObject);

但是如果我尝试使用相同的对象作为输出,我会得到一个“无效的被调用者”异常。此外,这也会产生同样的错误:

matlab = new MLApp.MLAppClass();

object myObject = new object();

matlab.GetWorkspaceData("myVariable", "base", out myObject);

这非常麻烦,因为我需要从Matlab获取大量数据到Visual Studio,而我实际上无法创建52K未初始化的变量并保留它们。有没有办法“取消初始化”变量?我在这里缺少一些概念吗?

3 个答案:

答案 0 :(得分:1)

在评论中解释@wonko79时,如果您想重复使用out变量,则应首先将其设置为null

以下是经过测试的示例calling MATLAB from C#

using System;

namespace CSharp_matlab_com
{
class Program
{
    static void Main(string[] args)
    {
        MLApp.MLAppClass matlab = new MLApp.MLAppClass();

        // create variables: a_0, a_1, ..., a_4
        for (int k = 0; k < 5; k++) {
            matlab.Execute(string.Format("a_{0} = rand(2);", k));
        }

        // retrieve variables from MATLAB and print their contents
        object a;
        for (int k = 0; k < 5; k++) {
            // current variable name
            string varname = string.Format("a_{0}", k);

            // get data array
            a = null;    // without this line, an exception is thrown!
            matlab.GetWorkspaceData(varname, "base", out a);

            // print contents
            var arr = (double[,]) a;
            Console.WriteLine("\nndims(a) = {0}, numel(a) = {1}", arr.Rank, arr.Length);
            for (int i = 0; i < arr.GetLength(0); i++) {
                for (int j = 0; j < arr.GetLength(1); j++) {
                    Console.WriteLine("{0}[{1},{2}] = {3}", varname, i, j, arr[i,j]);
                }
            }
        }
    }
}
}

输出:

ndims(a) = 2, numel(a) = 4
a_0[0,0] = 0.251806122472313
a_0[0,1] = 0.617090884393223
a_0[1,0] = 0.290440664276979
a_0[1,1] = 0.265280909810029

...

ndims(a) = 2, numel(a) = 4
a_4[0,0] = 0.425259320214135
a_4[0,1] = 0.16148474431175
a_4[1,0] = 0.312718886820616
a_4[1,1] = 0.178766186752368

答案 1 :(得分:0)

您可以为GetWorkspaceData方法创建一个包装器,如下一个示例所示:

public object GetData(string name)
{
    object data;
    mlApp.GetWorkspaceData(name, "base", out data);

    return data;
}

或者,更有用的通用包装器:

public T GetData<T>(string name)
{
    object data;
    mlApp.GetWorkspaceData(name, "base", out data);

    if (data == null)
        return default(T);

    if (data is T)
        return (T)data;
    else
        throw new InvalidCastException($"The variable '{name}', of type '{data.GetType().Name}' cannot be casted to type '{typeof(T).Name}'.");
}

答案 2 :(得分:0)

解决方案是将输出对象设置为null

我找到了here