NESHOM
NESHOM

Reputation: 929

Pass C# object[] to Matlab Dll method

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.

Upvotes: 1

Views: 1617

Answers (1)

Amro
Amro

Reputation: 124563

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);

Upvotes: 3

Related Questions