Main Content

Deploy MATLAB Function to Cross-Platform .NET 6.0 Application Using MWArray API

Supported Platform: Windows® (Authoring), Linux® (Execution), and macOS (Execution).

This example shows how to create a .NET assembly using the Library Compiler and integrate it into a .NET 5.0 application that can run on Linux or macOS.

Prerequisites

  1. Create a new work folder that is visible to the MATLAB® search path. This example uses C:\Work as the new work folder.

  2. Install MATLAB Runtime on Windows and on additional platforms where you plan on running your .NET application. For details, see Download and Install MATLAB Runtime.

  3. For Linux and macOS platforms, after installing MATLAB Runtime, you need to set the LD_LIBRARY_PATH and DYLD_LIBRARY_PATH environment variables respectively. For more information, see Set MATLAB Runtime Path for Deployment.

  4. 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.

Create MATLAB Function

Create a MATLAB file named mymagic.m with the following code:

function out = mymagic(in)
out = magic(in);
Test the MATLAB function at the command prompt.
y = mymagic(3)
y =
     8     1     6
     3     5     7
     4     9     2

Create .NET Assembly

Create a .NET assembly using the compiler.build.dotNETAssembly function.

buildResults = compiler.build.dotNETAssembly("mymagic.m",...
Interface="mwarray",...
Verbose="on", ...
AssemblyName="MyMatrixFunctions", ...
ClassName="MyMagic", ...
OutputDir=".\output")

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

The function produces a suite of files, as enumerated below, and places them in the specified output directory.

P:\MATLAB\WORK\OUTPUT
    GettingStarted.html
    includedSupportPackages.txt
    mccExcludedFiles.log
    MyMagic.cs
    MyMagicNative.cs
    MyMatrixFunctions.dll
    MyMatrixFunctions.xml
    MyMatrixFunctionsNative.dll
    MyMatrixFunctionsNative.xml
    MyMatrixFunctionsVersion.cs
    MyMatrixFunctions_overview.html
    readme.txt
    requiredMCRProducts.txt
    unresolvedSymbols.txt

No subfolders exist

Integrate MATLAB Code into .NET Application

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

  2. At the command line, type:

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

    This creates a folder named MyMagicConsoleApp that has the following contents:

    • obj folder

    • MyMagicConsoleApp.csproj project file

    • Program.cs C# source file

  3. Open the project file in a text editor.

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net6.0</TargetFramework>
      </PropertyGroup>
    
    </Project>

    Add the following references to the project using the <ItemGroup> tag:

    • MyMatrixFunctions.dll .NET assembly file created by the compiler.build.dotNETAssembly function.

    • MWArray.dll .NET assembly file dependency.

      If MATLAB is installed on your system

      • matlabroot\toolbox\dotnetbuilder\bin\win64\netstandard2.0\MWArray.dll

      If MATLAB Runtime is installed on your system

      • <MATLAB_RUNTIME_INSTALL_DIR>\toolbox\dotnetbuilder\bin\win64\netstandard2.0\MWArray.dll

    Once you add the references, your project file should resemble the following:

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net6.0</TargetFramework>
      </PropertyGroup>
    
        <ItemGroup>
        <Reference Include="MyMatrixFunctions">
          <HintPath>P:\MATLAB\work\output\MyMatrixFunctions.dll</HintPath>
    	  <!--Path to .NET Assembly created by compiler.build.dotNETAssembly function-->
        </Reference>
        <Reference Include="MWArray">
          <HintPath>C:\Program Files\MATLAB\R2024b\toolbox\dotnetbuilder\bin\win64\netstandard2.0\MWArray.dll</HintPath>
    	  <!--Path to MWArray.dll in the MATLAB-->
        </Reference>
      </ItemGroup>
    </Project>
  4. Replace the code in the Program.cs C# file with the following code:

     Program.cs

     Program.cs (macOS)

    The difference between the regular C# application code and the macOS version is that the original contents of the Main method now reside in a newly created function called MyMainFunc in the macOS version. The original Main method now simply calls the MWMCR.setupMacRunLoopAndRun method with MyMainFunc and the command-line arguments as parameters.

    MWMCR.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. Since .NET 6.0 or .NET Core applications on macOS do not by default set up a CFRunLoop on the main thread—where MATLAB relies on it for event management—MWMCR.setupMacRunLoopAndRun steps in to establish the CFRunLoop. This ensures seamless integration of MATLAB functions within a .NET 6.0 or .NET Core application running on macOS, preventing potential event handling issues.

    Note

    You need to use MWMCR.setupMacRunLoopAndRun only if you are developing or running you C# application on macOS.

  5. At the command line, build your project by typing:

    dotnet build MyMagicConsoleApp.csproj

Run C# Application

For testing purposes, you can run the application from MATLAB command prompt. This does not require a MATLAB Runtime. At the MATLAB command prompt, navigate to the directory containing the executable, and run your application by entering:

!dotnet run -- 3
The application displays the magic square matrix.
Magic square of order 3

     8     1     6
     3     5     7
     4     9     2 

Magic square as native array:
 
Element(0,0)= 8 
Element(0,1)= 1 
Element(0,2)= 6 
Element(1,0)= 3 
Element(1,1)= 5 
Element(1,2)= 7 
Element(2,0)= 4 
Element(2,1)= 9 
Element(2,2)= 2 

Integrate Using Visual Studio

As an alternative to the interactive command line approach to creating a .NET application, you can create a .NET application using Microsoft Visual Studio. If you have already created a .NET application using the above instructions, you can skip this section.

  1. Open Visual Studio and create a C# Console App named MyMagicConsoleApp. For details, see Create the app section in Create a .NET console application using Visual Studio.

  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. In the Solution Explorer, right-click the project name and select Add > Project Reference. In the Reference Manager window, click Browse and add the following references:

    • MyMatrixFunctions.dll .NET assembly file created by the compiler.build.dotNETAssembly function.

    • MWArray.dll .NET assembly file dependency.

      If MATLAB is installed on your system

      • matlabroot\toolbox\dotnetbuilder\bin\win64\netstandard2.0\MWArray.dll

      If MATLAB Runtime is installed on your system

      • <MATLAB_RUNTIME_INSTALL_DIR>\toolbox\dotnetbuilder\bin\win64\netstandard2.0\MWArray.dll

  5. Build the application.

Publish 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 MyMagicConsoleApp.csproj

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

    dotnet publish --configuration Release --framework net6.0 
      --runtime osx.10.11-x64 --self-contained true MyMagicConsoleApp.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.

Run .NET Application on Linux

  1. Copy the Release folder from ...\work\MyMagicConsoleApp\bin on Windows to ~/work on a Linux or macOS machine.

  2. On the Linux machine, verify that you have installed MATLAB Runtime and set up your library path environment variable. For more information, see Prerequisites.

  3. Open a command shell and navigate to:

    ~/work/Release/net6.0/<os-architecture>/publish
  4. Run the .NET application by typing:

    ./MyMagicConsoleApp 3
    Magic square of order 3
    
         8     1     6
         3     5     7
         4     9     2
    
    Magic square as native array:
    
    Element(0,0)= 8
    Element(0,1)= 1
    Element(0,2)= 6
    Element(1,0)= 3
    Element(1,1)= 5
    Element(1,2)= 7
    Element(2,0)= 4
    Element(2,1)= 9
    Element(2,2)= 2
    

See Also

| |

Related Topics