Main Content

Write MATLAB Code for Strongly Typed C# Interface

When creating a strongly typed C# interface to MATLAB® functions or classes, you can specify how to represent MATLAB data types in C# by using standard and custom data type mappings between MATLAB and C#. To specify the data type requirements, use an arguments block within a MATLAB function or a properties block and arguments block within a MATLAB class. For example, if your C# application code uses a double data type to represent a real scalar double value, its equivalent representation in MATLAB is (1,1) double {mustBeReal}.

MATLAB Function with Strongly Typed Data

This strongly typed MATLAB function specifies data type requirements using an arguments block.

function r = stronglyTypedFun(num)
arguments
    num (1,1) double {mustBeReal}
end
r = magic(num);

For more information about data type mappings, see Data Type Mappings Between .NET and Strongly Typed MATLAB Code. For more information about specifying data type requirements, see Function Argument Validation and Validate Property Values.

When you compile a strongly typed MATLAB function, class, or namespace, MATLAB generates C# code (.cs files). To generate the code from the MATLAB command prompt, call matlab.engine.typedinterface.generateCSharp.

The generated code:

  • Maps strongly typed MATLAB data types to C# data types.

  • Contains C# namespaces that correspond to MATLAB namespaces of the same name.

  • Contains C# classes that correspond to MATLAB classes of the same name.

  • Contains public C# methods that correspond to the public methods of MATLAB classes. The method names are unchanged and can be used as is in the C# application code. These aligned names eliminate the need for intermediate layer top-level functions that call the class methods through an feval function execution.

  • Contains C# get and set methods for public properties of MATLAB classes. The property names of MATLAB classes are prepended with get or set. For example, if the property name in a MATLAB class is X, the corresponding C# method names are get and set.

The strongly typed MATLAB class in this table specifies data type requirements using a properties block and an arguments block. The table shows how the strongly typed MATLAB class in a Shapes namespace is translated into C# source code.

MATLAB Value Class with Strongly Typed Data

Strongly Typed MATLAB Value ClassGenerated C# Code
classdef Position
%this is located in the Shapes namespace

    properties
        X (1,1) double {mustBeReal}
        Y (1,1) double {mustBeReal}
    end
 
    methods
        function P = show(P)
            arguments
                P (1,1) Shapes.Position
            end
            fprintf('%s: (%d, %d)\n', P.X, P.Y);
        end
    end
end
namespace Shapes
{
    struct Position {
        dynamic matlab;
        dynamic objRep;
         
        private void ThrowIfDefaultValue() {
            if (matlab == null || objRep == null) {
                throw new MATLABUnsupportedTypeException(
                    "Position object not initialized.");
            }
        }
  
        public double X {
            get {    
                ThrowIfDefaultValue();
                return objrep.X;
            }
            set {                      
                ThrowIfDefaultValue();
                objrep = matlab.internal.engine.setProperty(
                    objrep, "X", value);
            }
        }
 
        public double Y {
            get {     
                ThrowIfDefaultValue();
                return objrep.Y;      
            }
 
            set {    
                ThrowIfDefaultValue();
                objrep = matlab.internal.engine.setProperty(
                    objrep, "Y", value);
            }
        }
 
        public Position(MATLABProvider prov) {                
            if (prov == null)
                throw new ArgumentNullException(
                    "Error MATLAB instance not initialized.");
             matlab = prov;
             objrep = matlab.Position();
        }
 
        public Position(MATLABObject obj) {        
            if (!(obj as dynamic).isa("Circle"))
                throw new MATLABUnsupportedTypeException(
                    "Error object not a Circle.");
            objrep = obj;
            matlab = obj.GetMATLAB();
        }
 
        public void show() {                
            ThrowIfDefaultValue();
            objrep.show();
        }
 
        public static implicit operator MATLABObject(
            Position position) {
            position.ThrowIfDefaultValue();
            return position.objrep;
        }
    }
}

Sample C# Application Code

This C# code uses the MATLAB Engine and Data API for .NET. You can compile and run this C# application code.

using Mathworks.MATLAB.Engine;
using Mathworks.MATLAB.Types;
 
namespace CallGeneratedExample{
     
    class Main{
        public static void Main(string args []){
            dynamic eng = MATLABEngine.StartMATLAB();
            Shapes.Position p = new Shapes.Position(eng);
            p.show(); //outputs 0,0
            p.X = 5; //uses the set attribute of this property
            p.Y = p.X; //uses the get and set attributes of both properties
            double xVal = p.X;
            p.show();
        }
    }
}

Tip

  • When writing C# application code, specify the C# files generated by the matlab.engine.typedinterface.generateCSharp function and the Mathworks.MATLAB.Engine namespace as resources for the application by adding using statements.

  • Your MATLAB code must be strongly typed to leverage all the features of the interface. Otherwise, data type mapping between MATLAB and C# is absent, and you cannot use native C# data types.

  • During generation of the strongly typed interface, the matlab.engine.typedinterface.generateCSharp function retrieves type information from arguments and properties blocks. The retrieved information is array size, type, and whether it is a real number.

See Also

| |

Related Topics