Pass C# object[] to Matlab Dll method

倾然丶 夕夏残阳落幕 提交于 2019-12-11 13:45:23

问题


I am trying to pass a C# object array to a Matlab method using parameter array params keyword. My Matlab method is complied to a .net assembly Dll. Here is my simple c# method:

public void Method1(params object[] objArg)
{           
    _mMExt.mMethod1((MWArray[])objArg);
}

I am using varargin as input for my Matlab function mMethod1:

function mMethod1(varargin)
    nVarargs = length(varargin);
end

The issue is when I am converting object[] to MWArray[] by doing this:

(MWArray[])objArg

It seems that I can use (MWArray)object1 to convert C# object to MWArray, but it doesn't let me to convert an array of object to an array of MWArray.

Is this possible? if so, how?

Thanks in advance.


回答1:


Here is small example I tested.

Say you compiled the following MATLAB function into a .NET assembly using the MATLAB Compiler SDK:

myFunction.m

function myFunction(varargin)
    for i=1:nargin
        disp(varargin{i});
    end
end

Now in your C# program, you can simply call the function myLib.myClass.myFunction by passing it a variable number of input arguments like this:

Program.cs

using System;
using MathWorks.MATLAB.NET.Arrays;
using MathWorks.MATLAB.NET.Utility;
using myLib;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("calling myFunction(varargin)...");
        CallMyFunction(1, 2.0f, 3.14, "str4");
    }

    static void CallMyFunction(params MWArray[] varargin)  // or object[]
    {
        myClass obj = new myClass();
        obj.myFunction(varargin);
    }
}

This is equivalent to explicitly writing:

MWArray[] varargin = new MWArray[4];
varargin[0] = new MWNumericArray(1);
varargin[1] = new MWNumericArray(2.0f);
varargin[2] = new MWNumericArray(3.14);
varargin[3] = new MWCharArray("str4");

myClass obj = new myClass();
obj.myFunction(varargin);


来源:https://stackoverflow.com/questions/36608175/pass-c-sharp-object-to-matlab-dll-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!