Main Content

Deploy MATLAB Code Within .NET Application Using MATLAB Data API for .NET

Supported .NET Version: .NET 5.0 or higher recommended

This example shows how to create a .NET component from a MATLAB® function and integrate it with a .NET application written in C#. The workflow is supported on Windows®, Linux®, and macOS systems. However, .NET applications can only be published from Windows to Linux and macOS.

Prerequisites

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

  • Verify that you have met all of the MATLAB Compiler SDK™ .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 Install and Configure MATLAB Runtime.

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

  • Verify that you have .NET 5.0 SDK or higher or Microsoft® Visual Studio® 2019 or higher installed. If you have version 16.8.0 of Visual Studio 2019 installed, then you do not need to install .NET 5.0 or higher separately. You can verify whether .NET 5.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:

Create Function in MATLAB

In MATLAB, examine the MATLAB code that you want to package. For this example, create a MATLAB script named makesquare.m.

function y = makesquare(x)
y = magic(x);

At the MATLAB command prompt, enter makesquare(5).

The output is a 5-by-5 matrix.

    17    24     1     8    15
    23     5     7    14    16
     4     6    13    20    22
    10    12    19    21     3
    11    18    25     2     9

Create .NET Assembly Using compiler.build.dotNETAssembly

  1. Save the following code in a sample file named makesquareSample1.m:

    x = 5;
    y = makesquare(x);

  2. Build the .NET assembly using the compiler.build.dotNETAssembly function. Specify the interface type and sample file using name-value arguments.

    buildResults = compiler.build.dotNETAssembly('makesquare.m',...
    'Interface', 'matlab-data',...
    'SampleGenerationFiles','makesquareSample1.m');

    You can specify additional options in the compiler.build command by using name-value arguments. For details, see compiler.build.dotNETAssembly.

    The compiler.build.Results object buildResults contains information on the build type, generated files, included support packages, and build options.

    The function generates the following files in a folder named makesquaredotNETAssembly in your current working directory:

    • samples\makesquareSample1_mda.cs — C# .NET sample file.

    • GettingStarted.html — HTML file that contains steps on compiling .NET driver applications from the command line.

    • includedSupportPackages.txt — Text file that lists all support files included in the assembly.

    • makesquare.ctf — Archive containing MATLAB code.

    • mccExcludedFiles.log — Log file that contains a list of any toolbox functions that are not included in the application. For information on nonsupported functions, see MATLAB Compiler Limitations.

    • readme.txt — Text file that contains packaging and interface information.

    • requiredMCRProducts.txt — Text file that contains product IDs of products required by MATLAB Runtime to run the application.

    • unresolvedSymbols.txt — Text file that contains information on unresolved symbols.

    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

After creating your .NET component, you can integrate it into any .NET application. This example uses the sample C# application code generated during packaging as a starting point. You can use this sample .NET application code as a guide to write your own application.

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 only).

  1. Open the command prompt in Windows and navigate to the work folder.

  2. At the command line, enter:

    dotnet new console --framework net5.0 --name MakeSquareApp

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

    • obj folder

    • MakeSquareApp.csproj project file

    • Program.cs C# source file

  3. Copy the makesquare.ctf file generated by compiler.build.dotNETAssembly to the MakeSquareApp folder.

  4. Edit the project to add assembly dependencies and the makesquare.ctf archive file.

    1. Open the project file in a text editor and add the following assembly dependencies to the project using the <ItemGroup> tag:

      • MathWorks.MATLAB.Runtime.dll

      • MathWorks.MATLAB.Types.dll

       Windows Paths

       Linux and macOS Paths

    2. Include the makesquare.ctf archive file as a content file to the project.

      • Add the makesquare.ctf archive file as a content file within the <ItemGroup> tag.

      • Add the tag CopyToOutputDirectory and set it to Always. This step ensures that the makesquare.ctf file is copied to the output folder and can be used for debugging.

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

    Once you add the assembly dependencies and include makesquare.ctf as a content file, your project file looks like the following:

     Windows

     Linux

     macOS

  5. Replace the C# source file Program.cs with the sample file makesquareSample1_mda.cs:

     makesquareSample1_mda.cs

    The generated sample code has been edited by replacing the data type for the results variable from dynamic to double [,]. Also, a nested for loop to print the data in the results variable has been inserted.

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

    dotnet build MakeSquareApp.csproj
  7. At the command line, run your application by entering:

    dotnet run

    The application displays a 5-by-5 magic square.

        17    24     1     8    15
        23     5     7    14    16
         4     6    13    20    22
        10    12    19    21     3
        11    18    25     2     9

    Note

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

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

  2. Choose .NET 5.0 (Current) as the framework.

  3. Remove any source code (.cs) files that were created within your project.

  4. Add the makesquareSample1_mda.cs sample application code file generated by compiler.build.dotNETAssembly from the samples folder 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.

  5. Add the following assembly dependencies:

    • MathWorks.MATLAB.Runtime.dll

    • MathWorks.MATLAB.Types.dll

     Location of Assembly Dependencies

  6. Add the makesquare.ctf 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 makesquare.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 MakeSquareApp.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 MakeSquareApp.csproj project file looks like the following:

    ...
    <ItemGroup>
        <Content Include="makesquare.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 MakeSquareApp.exe.

  10. Run the application from Visual Studio by pressing Ctrl+F5. Alternatively, you can execute the generated executable from a system terminal:

    > cd C:\work\MakeSquareApp\MakeSquareApp\bin\Debug\net5.0
    > MakeSquareApp.exe

    The application returns the same output as the sample MATLAB code.

        17    24     1     8    15
        23     5     7    14    16
         4     6    13    20    22
        10    12    19    21     3
        11    18    25     2     9

    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.

Publish to Linux and macOS

Note

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 net5.0 
      --runtime linux-x64 --self-contained true MakeSquareApp.csproj

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

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

To publish to a specific platform, use the appropriate Runtime Identifier (RID). For details, see https://docs.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 net5.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\MakeSquareApp\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 Install and Configure MATLAB Runtime and Set MATLAB Runtime Path for Deployment.

  3. Open a Linux console and navigate to:

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

    chmod +x MakeSquareApp

  5. Run the application by entering:

    ./MakeSquareApp
        17    24     1     8    15
        23     5     7    14    16
         4     6    13    20    22
        10    12    19    21     3
        11    18    25     2     9

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.

See Also

| |

Related Topics

External Websites