Main Content

Pass .NET Objects to MATLAB Functions

This example shows how to pass .NET objects to a MATLAB function deployed within a C# application. The workflow is supported in Windows®, Linux®, and macOS systems.

Starting in R2024b, passing .NET objects to MATLAB® functions is supported on Linux and macOS systems. Before this version, it was only supported on Windows systems. If you encounter any issues on Windows, set the environment variable USE_DOTNETCLI2_WINDOWS to 1. (since R2024b)

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 ProcessMWObjectArray.m with the following code:

function result = ProcessMWObjectArray(obj)
    % Display the class type of the input
    disp(['Input is of type: ', class(obj)]);

    % Convert MWObjectArray to a MATLAB cell array
    matlabArray = cell(obj);

    % Display the contents and class type of each element in the array
    disp('Contents of the MWObjectArray:');
    for element = matlabArray
        disp(['Element: ', class(element{1})]);
        disp(element{1});
    end

    % Return the processed MATLAB array as the result
    result = matlabArray;
end

Use the NET.createArray function from the MATLAB external language interfaces API to create .NET objects in MATLAB and test the function.

% Create a .NET object array with different types
netArray = NET.createArray('System.Object', 4);
netArray(1) = int32(42);               % Integer
netArray(2) = 3.14;                    % Double
netArray(3) = 'Hello, MATLAB!';        % String
netArray(4) = NET.createArray('System.Int32', [1, 2, 3]);  % .NET array

% Convert the .NET object array to a MATLAB cell array for convenience
matlabArray = cell(netArray);

% Call the MATLAB function with the MATLAB array
result = ProcessMWObjectArray(matlabArray);

% Display the result
disp('Processed MATLAB array:');
disp(result);
Input is of type: cell
Contents of the MWObjectArray:
Element: int32
   42
Element: double
    3.1400
Element: System.String
Hello, MATLAB!

Element: System.Int32[,,]
  Int32[,,] with properties:

            Length: 6
        LongLength: 6
              Rank: 3
          SyncRoot: [1×1 System.Int32[,,]]
        IsReadOnly: 0
       IsFixedSize: 1
    IsSynchronized: 0
Processed MATLAB array:
    {[42]}    {[3.1400]}    {1×1 System.String}    {1×1 System.Int32[,,]}

When testing the ProcessMWObjectArray function from within MATLAB, you cannot directly convert a .NET object to an MWObjectArray. Therefore, a MATLAB cell array is used to mimic MWObjectArray behavior. Using a MATLAB cell array allows us to test the function directly in MATLAB since cell arrays can hold different types of data, similar to MWObjectArray. This makes them a good substitute for testing how the function processes various elements. When testing from a C# application, you can create a .NET array and convert it to an MWObjectArray to pass to the MATLAB function.

Create .NET Assembly

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

buildResults = compiler.build.dotNETAssembly("ProcessMWObjectArray.m", ...
    Interface="mwarray",...
    Verbose="on", ...
    OutputDir=".\output", ...
    AssemblyName="MATLABExample", ClassName="MyMATLABFunctions")

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
    MATLABExample.dll
    MATLABExample.xml
    MATLABExampleNative.dll
    MATLABExampleNative.xml
    MATLABExampleVersion.cs
    MATLABExample_overview.html
    mccExcludedFiles.log
    MyMATLABFunctions.cs
    MyMATLABFunctionsNative.cs
    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 DotNetObjConsoleApp

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

    • obj folder

    • DotNetObjConsoleApp.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:

    • MATLABExample.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 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="MATLABExample">
          <HintPath>P:\MATLAB\work\output\MATLABExample.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 DotNetObjConsoleApp.csproj

Run .NET Application

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

!DotNetObjConsoleApp.exe
Input is of type: System.Object[]

Contents of the MWObjectArray:

Element: int32

   42

Element: double

    3.1400

Element: System.String

Hello, MATLAB!

Element: System.Int32[]

  Int32[] with properties:

            Length: 3
        LongLength: 3
              Rank: 1
          SyncRoot: [1x1 System.Int32[]]
        IsReadOnly: 0
       IsFixedSize: 1
    IsSynchronized: 0

[42]    [3.1400]    [1x1 opaque]    [1x1 opaque]

See Also

|