Main Content

Deploy MATLAB Classes to .NET Application Using MATLAB Data API for .NET

Supported .NET Version: .NET 6.0 or higher

Data API: MATLAB® Data Array for .NET

This example shows how to package MATLAB classes contained within a MATLAB package and deploy it to a C# application. It uses the MATLAB Data API for .NET for managing data exchange between the MATLAB code and the C# application. The MATLAB classes are accessed via a front-facing MATLAB function. The workflow is supported on Windows®, Linux®, and macOS.

Since R2023b, .NET applications with packaged MATLAB code containing MATLAB classes can be developed and published across Windows, Linux, and macOS platforms. This means it's possible to develop on any one of these platforms and publish to any of the other two.

Note that while development and publishing can happen on any platform, there may still be platform-specific nuances and issues. Some libraries or functionalities might behave differently on different platforms, and developers should test their applications thoroughly on the target platform to ensure expected behavior.

Prerequisites

  • Create a new work folder that is visible to the MATLAB search path. This example uses a folder named work.

  • Verify that you have set up a .NET development environment. For details, see Set Up .NET Development Environment.

  • Verify that you have met all of the MATLAB .NET target requirements. For details, see MATLAB Compiler SDK .NET Target Requirements.

  • End users must have an installation of MATLAB Runtime to run the application. For details, see Download and Install MATLAB Runtime.

    For testing purposes, you can use an installation of MATLAB instead of MATLAB Runtime.

  • Verify that you have .NET 6.0 SDK or higher or Microsoft® Visual Studio® 2022 (v17.0 or higher) installed. You can verify whether .NET 6.0 is installed by entering dotnet --info at a system command prompt. You can download a .NET SDK version specific to your operating system from https://dotnet.microsoft.com/download.

Data Management

To exchange data between the deployed MATLAB code and the .NET application, use the MATLAB Data API for .NET. This API is also used by MATLAB Engine. For an overview, see Call MATLAB from .NET. For details, see:

Files

Purpose of Each Example File

FilesPurpose
+shapesPackage containing two classes: MyPosition.m and MyRectangle.m.
MyPosition.mClass within the +shapes package that accepts the X and Y coordinates of a point and creates a MyPosition object.
MyRectangle.mClass within the +shapes package that accepts two points specified as MyPosition objects and creates a MyRectangle object.
calculatearea.mFunction that accepts a MyRectangle object as input and calculates the area of the rectangle.
Program.csC# application code that integrates the code archive (.ctf file) and C# code (.cs files) generated by packaging the MATLAB code.

Create MATLAB Function and Classes

  1. Examine the code for MyPosition.m, MyRectangle.m, and calculatearea.m.

    • The +shapes package contains two MATLAB classes: MyPosition.m and MyRectangle.m.

    • The calculatearea.m MATLAB function located outside of the +shapes package accepts a MyRectangle object as input and calculates the area of the rectangle.

     +shapes (Package)

     MyPosition.m (Class)

     MyRectangle.m (Class)

     calculatearea.m (Function)

    Established MATLAB users may find it unconventional to see a properties block in a class and an arguments block in a method or function, each detailed with data type information. Both blocks let you represent C# data types with an equivalent MATLAB type. For instance, if your C# application employs a double data type representing a value, you can now represent that in MATLAB as a double. You can also specify a MATLAB object as an argument or property type. For example, the MyRectangle class specifies shapes.MyPosition as the type for the UpperLeft and LowerRight properties of the MyRectangle class. For details, see Data Type Mappings Between C++ and Strongly Typed MATLAB Code.

    In this example, properties and arguments blocks with data type information are used to illuminate subtle nuances. However, remember that including type information is entirely optional. The deployment process remains unchanged even without it. Nonetheless, adding type information to your MATLAB code can greatly simplify the process of writing C# application code and decrease errors caused by type conversion. Various parts of this example underscore the areas where this difference manifests.

  2. Create a MATLAB script named runshapes.m with the following code and execute it at the MATLAB command prompt. This script illustrates how the classes and function interact to generate an output.

     runshapes.m

    runshapes
    Rectangle 1
    Point 1 = (10, 5)
    
    Point 2 = (50, 20)
    
    Rectangle (10, 5) -> (50, 20)
    
    Rectangle 2
    Point 1 = (0, -5)
    
    Point 2 = (60, 30)
    
    Rectangle (0, -5) -> (60, 30)
    
    Area of rectangle r1 = 600
    Area of rectangle r2 = 2100

Create .NET Assembly Using compiler.build.dotNETAssembly

To create a .NET assembly use the compiler.build.dotNETAssembly function.

files = ["calculatearea.m", "+shapes"];
buildResults = compiler.build.dotNETAssembly(files, Interface="matlab-data",...
    AssemblyName="CalculateArea", OutputDir=".\output", Verbose="on")
P:\MATLAB\WORK\OUTPUT
│   CalculateArea.csproj
│   CalculateArea.ctf
│   CalculateArea.deps.json
│   CalculateArea.dll
│   GettingStarted.html
│   includedSupportPackages.txt
│   mccExcludedFiles.log
│   readme.txt
│   requiredMCRProducts.txt
│   unresolvedSymbols.txt
│
└───strongly_typed_interface
        calculatearea.cs
        shapes_MyPosition.cs
        shapes_MyRectangle.cs

The function produces a suite of files, as enumerated above, and places them in the specified output directory. Among these, the key files utilized during the integration process are:

  • CalculateArea.ctf—the code archive containing packaged MATLAB code.

  • calculatearea.cs, shapes_MyPosition.cs, and shapes_MyRectangle.cs—C# code files.

  • CalculateArea.dll—.NET assembly file.

For information on the other files, see Files Generated After Packaging MATLAB Functions.

Although supplying an assembly name to the compiler.build.dotNETAssembly function via the AssemblyName property isn't mandatory, it's highly recommended. Doing so results in a cleaner namespace for the generated .NET assembly and C# files. In its absence, a root namespace named example is automatically appended to the sub-namespace, leading to a cluttered and potentially confusing namespace structure.

To finalize integration, you can choose one of two options:

  • Use the CalculateArea.ctf code archive file in conjunction with the calculatearea.cs, shapes_MyPosition.cs, and shapes_MyRectangle.cs C# code files. This is option is useful if you want to examine the MATLAB to C# translation and make modifications.

  • Use the CalculateArea.ctf code archive file in conjunction with the CalculateArea.dll assembly file. This option is useful if you want to utilize the MATLAB code's functionality within the .NET application without delving into specific of the C# translation.

Upon inspection, you notice that the function also generates a CalculateArea.csproj project file. This file is generated specifically to create the corresponding CalculateArea.dll .NET assembly file. However, it should not be mistaken as a template for your .NET project and must not be used in that context. If you modify the C# code files that were generated by compiler.build.dotNETAssembly and need to create a .NET assembly, then in that case, use this project file by executing: dotnet build CalculateArea.csproj.

This example employs the first integration option to illustrate type mapping mechanics. Relevant guidance for using the second option is interjected at pertinent stages of the workflow.

You can inspect the content of the C# code file below:

 calculatearea.cs

For an in-depth discussion of how the MATLAB classes and function are mapped to C#, see Mapping MATLAB Classes and Functions to C#.

Note

The generated component does not include MATLAB Runtime or an installer. To create an installer using the buildResults object, see compiler.package.installer.

Integrate MATLAB Code into .NET Application

You can finalize the integration process in your preferred C# development environment, including a text editor along with the .NET SDK Command Line API, or alternatives such as Microsoft Visual Studio on Windows and macOS. This example shows you how to complete the integration using both options. For details, see Set Up .NET Development Environment.

Use .NET SDK Command Line API to Build Application

If you are using Microsoft Visual Studio, see Use Microsoft Visual Studio to Build Application (Windows).

  1. Open the command prompt in Windows and navigate to the work folder being used in this example.

  2. At the command line, enter:

    dotnet new console --framework net6.0 --name ShapesConsoleApp

    This command creates a folder named ShapesConsoleApp that contains the following:

    • obj folder

    • ShapesConsoleApp.csproj project file

    • Program.cs C# source file

  3. Copy the following files produced by the compiler.build.dotNETAssembly function to the project folder created by dotnet new, alongside the Program.cs C# application code file:

    • calculatearea.cs, shapes_MyPosition.cs, and shapes_MyRectangle.cs C# wrapper files from the ...\work\output\strongly_typed_interface\ directory.

    • CalculateArea.ctf code archive from the ...\work\output directory.

  4. Edit the project file to add MathWorks assembly dependencies and the CalculateArea.ctf code archive file.

    1. Open the project file in a text editor and include the following MathWorks assemblies using a <Reference> tag within the <ItemGroup> tag of the project:

      • MathWorks.MATLAB.Runtime.dll

      • MathWorks.MATLAB.Types.dll

       Windows Paths to MathWorks Assemblies

       Linux and macOS Paths to MathWorks Assemblies

      Note

      If you use the CalculateArea.dll assembly file generated by the compiler.build.dotNETAssembly function instead of the C# code files, include that as a Reference within the same <ItemGroup> tag.

    2. Include the CalculateArea.ctf code archive file as a Content file to the project.

      • Add the CalculateArea.ctf code archive file as a Content file within the <ItemGroup> tag.

      • Add the tag CopyToOutputDirectory and set it to Always. This step ensures that the CalculateArea.ctf file is copied to the output folder during the build process. This means that when you build your project, this file is in the same directory as your built .exe file.

      • Add the tag CopyToPublishDirectory and set it to Always. This step ensures that the CalculateArea.ctf file is copied to the cross-platform folder to which this project is published.

    Once you add the assembly dependencies and include CalculateArea.ctf as a Content file, your project file looks as follows:

     ShapesConsoleApp.csproj (Windows)

     ShapesConsoleApp.csproj (Linux)

     ShapesConsoleApp.csproj (macOS)

    Note

    If you choose to use the CalculateArea.dll .NET assembly—generated by compiler.build.dotNETAssembly—over the C# code files, remember to uncomment the Reference tags to the CalculateArea.dll in the project file. This change ensures your project correctly uses the assembly file.

  5. Replace the code in the Program.cs C# file with the following code:

     Program.cs

    Note

    While developing and operating on macOS systems, transition the code from the Main method into a new function named MainFunc. Subsequently, invoke MATLABRuntime.SetupMacRunLoopAndRun from within the Main method and pass MainFunc along with the command-line arguments as parameters. MATLABRuntime.SetupMacRunLoopAndRun is integral for macOS environments because it lets MATLAB interact with the Core Foundation Run Loop (CFRunLoop), a macOS-specific mechanism for handling events such as user inputs or timer events. For details, see MathWorks.MATLAB.Runtime.MATLABRuntime.

  6. At the command line, build your project by entering:

    dotnet build ShapesConsoleApp.csproj

Run C# Application

For testing purposes, you can run the application from the MATLAB command prompt. This does not require a MATLAB Runtime installation.

At the MATLAB command prompt, navigate to the work\ShapesConsoleApp\ShapesConsoleApp\bin\Debug\net6.0 directory and run the executable by typing:

!dotnet run

The application displays the output.

Rectangle 1
Point 1 = (10, 5)
Point 2 = (50, 20)
Rectangle (10, 5) -> (50, 20)
Rectangle 2
Point 1 = (0, -5)
Point 2 = (60, 30)
Rectangle (0, -5) -> (60, 30)
Area of rectangle r1 = 600
Area of rectangle r1 = 2100
Perimeter of rectangle r1 is = 110
Perimeter of rectangle r2 is = 190

Note

When you're ready to deploy this application, ensure the target system has MATLAB Runtime installed. For details, see Download and Install MATLAB Runtime. On Linux and macOS systems, you must set the LD_LIBRARY_PATH and DYLD_LIBRARY_PATH runtime paths respectively, prior to running your application. For details, see Set MATLAB Runtime Path for Deployment.

Use Microsoft Visual Studio to Build Application (Windows)

  1. Open Microsoft Visual Studio and create a C# Console App named ShapesConsoleApp.

  2. Choose .NET 6.0 (Long-term support) as the framework.

  3. Swap out the default-generated source code in the Program.cs file with the specific source code provided in the Program.cs file found on this example page.

  4. Incorporate the calculatearea.cs, shapes_MyPosition.cs, and shapes_MyRectangle.cs C# code files generated by the compiler.build.dotNETAssembly function, by navigating to Solution Explorer, right-clicking your project, and selecting Add > Existing Item. Use the dialog box to find and add the C# code files.

    Note

    If you prefer to use the CalculateArea.dll assembly file produced by the compiler.build.dotNETAssembly function, right-click your solution in Solution Explorer and choose Edit Project File. Here, you'll need to add a reference to the CalculateArea.dll file within the existing <ItemGroup> tag.

    Refer to one of the project files listed above for guidance.

  5. Add the following MathWorks assembly dependencies:

    • MathWorks.MATLAB.Runtime.dll

    • MathWorks.MATLAB.Types.dll

     Location of MathWorks Assemblies

  6. Add the CalculateArea.ctf code archive file as a Content file to the project. Right-click your project in Solution Explorer and select Add > Existing Item. In the dialog box, browse for the file and add the file.

  7. Right-click the CalculateArea.ctf file in Solution Explorer and select Properties. In the Properties window, set Build Action to Content and Copy to Output Directory to Copy always.

  8. Right-click your project in Solution Explorer and select Edit Project File. The ShapesConsoleApp.csproj project file opens in the editor. Add the <CopyToPublishDirectory> tag right below the <CopyToOutputDirectory> tag and set it to Always. The edited portion of the ShapesConsoleApp.csproj project file looks as follows:

    ...
    <ItemGroup>
        <Content Include="CalculateArea.ctf">
          <CopyToOutputDirectory>Always</CopyToOutputDirectory>
          <CopyToPublishDirectory>Always</CopyToPublishDirectory>
        </Content>
    </ItemGroup>
    ...

  9. On the menu bar, choose Build and choose Build Solution to build the application within Visual Studio.

    The build process generates an executable named ShapesConsoleApp.exe.

  10. Tip

    If you are unable to run your application from Visual Studio, open the Developer Command Prompt for Visual Studio and start Visual Studio by entering devenv /useenv. Then, open your project and run your application.

Run C# Application from Within Visual Studio

Before executing your C# application in Visual Studio, ensure that your PATH environment variable is correctly set to reference your MATLAB or MATLAB Runtime installation. Here's how you can set the PATH environment variable within Visual Studio:

  1. In Visual Studio, right-click your project in Solution Explorer, then click Properties.

  2. Navigate to Debug > General, and select Open debug launch profiles UI.

  3. In the Launch Profiles window, under Environment variables, set your PATH:

    • For MATLAB:

      PATH=C:\Program Files\MATLAB\R2024b\runtime\win64
    • For MATLAB Runtime:

      PATH=C:\Program Files\MATLAB\MATLAB Runtime\R2024b\runtime\win64

Run the application from Visual Studio by pressing Ctrl+F5.

Publish to Linux and macOS

Note

Before R2023a: Applications can only be published from Windows to Linux and macOS.

  • To publish the application to Linux, enter the following command on a single line at the system command prompt:

    dotnet publish --configuration Release --framework net6.0 
      --runtime linux-x64 --self-contained true ShapesConsoleApp.csproj

  • To publish application to macOS, enter the following command on a single line:

    dotnet publish --configuration Release --framework net6.0 
      --runtime osx.12-x64 --self-contained true ShapesConsoleApp.csproj

To publish to a specific platform, use the appropriate Runtime Identifier (RID). For details, see https://learn.microsoft.com/en-us/dotnet/core/rid-catalog.

Publish from Visual Studio

For details on how to set up publishing from Visual Studio, see the .NET documentation. Once setup is complete, edit your publish profile to contain the following settings:

  • Set Configuration to Release | Any CPU.

  • Set Target framework to net6.0.

  • Set Deployment mode to Self-contained.

  • Set Target runtime to linux-x64 or osx-x64.

  • Leave Target location unchanged or set it to a location of your choice.

Run Published Application on Linux

  1. Copy the Release folder from C:\work\ShapesConsoleApp\bin on Windows to ~/work on a Linux machine. Create a work folder on Linux if one does not already exist.

  2. On the Linux machine, verify that you have installed MATLAB Runtime and set up your LD_LIBRARY_PATH environment variable. For details, see Download and Install MATLAB Runtime and Set MATLAB Runtime Path for Deployment.

  3. Open a Linux console and navigate to:

    ~/work/Release/net6.0/linux-x64/publish
  4. Add execute permissions to the Linux executable:

    chmod +x ShapesConsoleApp

  5. Run the application by entering:

    ./ShapesConsoleApp

Follow similar steps to run the application on macOS.

Note

You can use .NET Framework version 4.6.1 or higher to implement this example. However, you cannot deploy the example across platforms. Also, .NET Framework has no command-line interface.

Related Topics