Contenu principal

Build .NET Core Application That Runs on Linux and macOS

R2026b

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

This example shows how to create a .NET assembly using the .NET Assembly Compiler and integrate it into a .NET Core 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 Core 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 Library Paths for Deployment.

  4. Verify that you have Visual Studio® and .NET Core 2.0 or higher installed. If you have version 15.8.2 of Visual Studio 2017 installed, then you do not need to install .NET Core 2.0 or higher separately.

Create .NET Assembly

Package the function into a .NET assembly using the .NET Assembly Compiler app. Alternatively, if you want to create a .NET assembly from the MATLAB command window using a programmatic approach, see compiler.build.dotNETAssembly.

  1. Create a new MATLAB file named mymagic.m with the following code in the work folder:

    function out = mymagic(in)
    out = magic(in);
  2. Type dotNetAssemblyCompiler at the MATLAB command line to launch the .NET Assembly Compiler app.

  3. In the Exported Functions section, click the Add Exported Function button to add the file mymagic.m to the project.

  4. In the .NET Assembly Info section, name the library MyMatrixFunctions.

  5. In the Build Settings section, rename the class Class1 as MyMagic.

  6. Select Build and Package to create a .NET assembly and installer. For information about the created files, see Files Generated After Packaging MATLAB Functions.

Create .NET Core Application

  1. Open the command prompt in Windows and navigate to the folder C:\Work.

  2. At the command line, type:

    dotnet new console --name MyDotNetCoreApp

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

    • obj folder

    • MyDotNetCoreApp.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>netcoreapp2.0</TargetFramework>
      </PropertyGroup>
    
    </Project>

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

    • .NET assembly file MyMatrixFunctions.dll created by the .NET Assembly Compiler app

    • MWArray.dll, which is located in <MATLAB_RUNTIME_INSTALL_DIR>\toolbox\dotnetbuilder\bin\win64\<framework_version>

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

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>netcoreapp2.2</TargetFramework>
      </PropertyGroup>
    
        <ItemGroup>
        <Reference Include="MyMatrixFunctions">
          <HintPath>C:\work\MyMatrixFunctions\output\MyMatrixFunctions.dll</HintPath>
    	  <!--Path to .NET Assembly created by .NET Assembly Compiler app-->
        </Reference>
        <Reference Include="MWArray">
          <HintPath>C:\Program Files\MATLAB\MATLAB Runtime\R2026b\toolbox\dotnetbuilder\bin\win64\v4.0\MWArray.dll</HintPath>
    	  <!--Path to MWArray.dll in the MATLAB Runtime-->
        </Reference>
      </ItemGroup>
    </Project>
  4. Open the C# source file Program.cs and replace the existing code with the following code:

    // *******************************************************************************
    //
    // Program.cs
    //
    // This example demonstrates how to use MATLAB .NET Assembly to build a simple 
    // component returning a magic square and how to convert MWNumericArray types
    // to native .NET types.
    //
    // Copyright 2001-2019 The MathWorks, Inc.
    //
    // *******************************************************************************
    
    using System;
    
    using MathWorks.MATLAB.NET.Utility;
    using MathWorks.MATLAB.NET.Arrays;
    
    using MyMatrixFunctions;
    
    namespace MathWorks.Examples.MagicSquare
    {
    	/// <summary>
    	/// The MagicSquareApp class computes a magic square of the user specified size.  
    	/// </summary>
    	/// <remarks>
    	/// args[0] - a positive integer representing the size of the magic square.
    	/// </remarks>
    	class Program
    	  {
          #region MAIN
    
    		  /// <summary>
    		  /// The main entry point for the application.
    		  /// </summary>
    		  [STAThread]
    		  static void Main(string[] args)
    		    {
              MWNumericArray? arraySize= null; 
              MWNumericArray? magicSquare= null;
    
              try
                {
                  // Get user specified command line arguments or set default
                  arraySize= (0 != args.Length) ? Double.Parse(args[0]) : 4;
    
                  // Create the magic square object
                  MyMagic magic= new MyMagic();
    
                  // Compute the magic square and print the result
                  magicSquare= (MWNumericArray)magic.mymagic(arraySize);
    
                  Console.WriteLine("Magic square of order {0}\n\n{1}", arraySize, magicSquare);
    
                  // Convert the magic square array to a two dimensional native double array
                  double[,] nativeArray= (double[,])magicSquare.ToArray(MWArrayComponent.Real);
    
                  Console.WriteLine("\nMagic square as native array:\n");
    
                  // Display the array elements:
                  for (int i= 0; i < (int)arraySize; i++) 
                    for (int j= 0; j < (int)arraySize; j++)
                      Console.WriteLine("Element({0},{1})= {2}", i, j, nativeArray[i,j]);
    
                  Console.ReadLine();  // Wait for user to exit application
                }
    
              catch(Exception exception)
                {
                  Console.WriteLine("Error: {0}", exception);
                }
            }
    
          #endregion
    	  }
      }
  5. At the command line, build your .NET Core project by typing:

    dotnet build MyDotNetCoreApp.csproj
  6. At the command line, run your application by typing:

    dotnet run -- 3

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

  7. Publish the project as a self-contained deployment to execute the application on either Linux or macOS.

    • To publish to Linux, type the following command on a single line:

      dotnet publish --configuration Release --framework netcoreapp2.2 
        --runtime linux-x64 --self-contained true MyDotNetCoreApp.csproj

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

      dotnet publish --configuration Release --framework netcoreapp2.2 
        --runtime osx.10.11-x64 --self-contained true MyDotNetCoreApp.csproj

Run .NET Core Application on Linux

  1. Copy the Release folder from C:\Work\MyDotNetCoreApp\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/netcoreapp2.2/<os-architecture>/publish
  4. Run the .NET Core application by typing:

    ./MyDotNetCoreApp 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

Topics