Deploy MATLAB Function That Accepts Struct Array as Input Argument to .NET Application
Supported .NET Version: .NET 6.0 or higher
Data API: MATLAB® Data Array for .NET
This example shows how to package a MATLAB function that accepts a struct array as input and deploy it with a .NET application written in C#. The workflow is supported on Windows®, Linux®, and macOS systems. This example uses a workflow based on Windows.
Since R2023a, .NET applications with packaged MATLAB code 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. Prior to that release, .NET applications could only be published from Windows to Linux and macOS.
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:
Create MATLAB Function
Create a MATLAB file named analyzeData.m
with the following code:
function outputStruct = analyzeData(inputStruct) % This function takes a MATLAB struct 'inputStruct' as input, performs % statistical analysis on each numeric field, and returns a struct % 'outputStruct' containing the results of these analyses. Non-numeric % fields in the input struct are ignored. % % Inputs: % inputStruct - Struct with fields containing numeric data. % % Outputs: % outputStruct - Struct with the same fields as 'inputStruct'. Each % field is a struct with 'mean', 'std', and 'max' % of the corresponding field in 'inputStruct'. % % Use arguments block to map a MATLAB type to a C# type % Struct arrays in MATLAB map to a MATLAB Data Array % MATLABStruct type in C# arguments (Input) inputStruct (1,1) struct end arguments (Output) outputStruct (1,1) struct end % Initialize outputStruct outputStruct = struct(); % Get field names from the input struct fields = fieldnames(inputStruct); % Loop over each field and perform analysis for i = 1:length(fields) fieldName = fields{i}; % Ensure the field contains numeric data if isnumeric(inputStruct.(fieldName)) % Calculate mean outputStruct.(fieldName).mean = mean(inputStruct.(fieldName)); % Calculate standard deviation outputStruct.(fieldName).std = std(inputStruct.(fieldName)); % Calculate max value outputStruct.(fieldName).max = max(inputStruct.(fieldName)); else warning('Field %s is not numeric and was skipped.', fieldName); end end end
Established MATLAB users may find the presence of an arguments
block unconventional. The arguments
block lets you represent C# data
types with an equivalent MATLAB type.
Test the MATLAB function at the command prompt.
data = struct(); data.temperatures = [72, 75, 69, 68, 70]; data.pressures = [30, 29.5, 30.2, 29.9, 30.1]; output = analyzeData(data) output.temperatures(:) output.pressures(:)
output = struct with fields: temperatures: [1×1 struct] pressures: [1×1 struct] ans = struct with fields: mean: 70.8000 std: 2.7749 max: 75 ans = struct with fields: mean: 29.9400
Create .NET Assembly Using compiler.build.dotNETAssembly
Create a code archive (.ctf
file), from the MATLAB function using the compiler.build.dotNETAssembly
function.
buildResults = compiler.build.dotNETAssembly("analyzeData.m", Interface="matlab-data",... Verbose="on", OutputDir=".\output", AssemblyName="AnalyzeData")
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 and C# file. 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. Among these, the key files utilized during
the integration process are the code archive (.ctf
file) containing the
MATLAB code, a C# (.cs
) code file, and a .NET assembly
(.dll
file). For information on the other files, see Files Generated After Packaging MATLAB Functions.
P:\MATLAB\WORK\OUTPUT │ AnalyzeData.csproj │ AnalyzeData.ctf │ AnalyzeData.deps.json │ AnalyzeData.dll │ GettingStarted.html │ includedSupportPackages.txt │ mccExcludedFiles.log │ readme.txt │ requiredMCRProducts.txt │ unresolvedSymbols.txt │ └───strongly_typed_interface analyzeData.cs
To finalize integration, you can choose one of two options:
Use the
AnalyzeData.ctf
code archive file in conjunction with theanalyzeData.cs
C# code file.Use the
AnalyzeData.ctf
code archive file in conjunction with theAnalyzeData.dll
.NET assembly file.
Upon inspection, you notice that the function also generates a
AnalyzeData.csproj
project file. This file is generated specifically
to create the corresponding AnalyzeData.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.
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:
In the analyzeData.cs
C# code file, the MATLAB function's struct
argument specification maps to a
MATLAB Data Array based C# equivalent, MATLABStruct
.
arguments (Input) inputStruct (1,1) struct end |
MATLABStruct inputStruct |
arguments (Output) outputStruct (1,1) struct end |
public static void analyzeData(MATLABProvider _matlab, MATLABStruct inputStruct, out MATLABStruct outputStruct){ dynamic _dynMatlab = _matlab; outputStruct = (MATLABStruct)_dynMatlab.analyzeData(new RunOptions(nargout:1),inputStruct); } |
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).
Open the command prompt in Windows and navigate to the
work
folder being used in this example.At the command line, enter:
dotnet new console --framework net6.0 --name StructConsoleApp
This command creates a folder named
StructConsoleApp
that contains the following:obj
folderStructConsoleApp.csproj
project fileProgram.cs
C# source file
Copy the following files produced by the
compiler.build.dotNETAssembly
function to the project folder created bydotnet new
, alongside theProgram.cs
C# application code file:.cs
C# wrapper files from the...\work\output\strongly_typed_interface\
directory.AnalyzeData.ctf
code archive from the...\work\output
directory.
Edit the project to add assembly dependencies and the
AnalyzeData.ctf
code archive file generated by thecompiler.build.dotNETAssembly
function.Open the project file in a text editor and include the following assemblies using a
<Reference>
tag within the<ItemGroup>
tag of the project:MathWorks.MATLAB.Runtime.dll
MathWorks.MATLAB.Types.dll
Note
If you use the
AnalyzeData.dll
.NET assembly generated by thecompiler.build.dotNETAssembly
function instead of the C# code file, include that as a reference within the same<ItemGroup>
tag.Include the
AnalyzeData.ctf
code archive file as a content file to the project.Add the
AnalyzeData.ctf
code archive file as a content file within the<ItemGroup>
tag.Add the tag
CopyToOutputDirectory
and set it toAlways
. This step ensures that theAnalyzeData.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 toAlways
. This step ensures that theAnalyzeData.ctf
file is copied to the cross-platform folder to which this project is published.
Once you add the assembly dependencies and include
AnalyzeData.ctf
as a content file, your project file looks like the following:StructConsoleApp.csproj
(Windows)StructConsoleApp.csproj
(Linux)StructConsoleApp.csproj
(macOS)Note
If you choose to use the
AnalyzeData.dll
.NET assembly—generated bycompiler.build.dotNETAssembly
—over the C# code file, remember to uncomment the reference tags to theAnalyzeData.dll
in the project file. This change ensures your project correctly uses the.dll
file.Replace the code in the
Program.cs
C# file with the following code:Note
While developing and operating on macOS systems, transition the code from the
Main
method into a new function namedMainFunc
. Subsequently, invokeMATLABRuntime.SetupMacRunLoopAndRun
from within theMain
method and passMainFunc
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, seeMathWorks.MATLAB.Runtime.MATLABRuntime
.At the command line, build your project by entering:
dotnet build StructConsoleApp.csproj
Run C# Application
For testing purposes, you can run the application from MATLAB command prompt. This does not require a MATLAB Runtime installation.
At the MATLAB command prompt, navigate to the directory containing the executable, and run your application by entering:
!dotnet run
The application displays the mean values.
Field: temperatures mean: 70.8000 std: 2.7749 max: 75.0000 Field: pressures mean: 29.9400 std: 0.2702 max: 30.2000
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)
Open Microsoft Visual Studio and create a C# Console App named
StructConsoleApp
.Choose
.NET 6.0 (Long-term support)
as the framework.Swap out the default-generated source code in the
Program.cs
file with the specific source code provided in theProgram.cs
file found on this example page.Choose one of two options:
To incorporate the
analyzeData.cs
C# code file generated by thecompiler.build.dotNETAssembly
function, navigate to Solution Explorer, right-click your project, and select Add > Existing Item. Use the dialog box to find and add theanalyzeData.cs
C# code file.If you prefer to use the
AnalyzeData.dll
.NET assembly produced by thecompiler.build.dotNETAssembly
function, right-click your solution in Solution Explorer and choose Edit Project File. Here, you'll need to add a reference to theAnalyzeData.dll
file within the existing<ItemGroup>
tag.
View one of the above-listed project files as a reference.
Add the following assembly dependencies:
MathWorks.MATLAB.Runtime.dll
MathWorks.MATLAB.Types.dll
Add the
AnalyzeData.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.Right-click the
AnalyzeData.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.Right-click your project in Solution Explorer and select Edit Project File. The
StructConsoleApp.csproj
project file opens in the editor. Add the<CopyToPublishDirectory>
tag right below the<CopyToOutputDirectory>
tag and set it toAlways
. The edited portion of theStructConsoleApp.csproj
project file looks as follows:... <ItemGroup> <Content Include="AnalyzeData.ctf"> <CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToPublishDirectory>Always</CopyToPublishDirectory> </Content> </ItemGroup> ...
On the menu bar, choose Build and choose Build Solution to build the application within Visual Studio.
The build process generates an executable named
StructConsoleApp.exe
.Run the application from Visual Studio by pressing Ctrl+F5. Alternatively, you can execute the generated executable from a system terminal:
> cd C:\work\StructConsoleApp\StructConsoleApp\bin\Debug\net6.0 > StructConsoleApp.exe
The application returns the same output as the sample MATLAB code.
Field: temperatures mean: 70.8000 std: 2.7749 max: 75.0000 Field: pressures mean: 29.9400 std: 0.2702 max: 30.2000
Tip
If you are unable to build your application, change the solution platform from
Any CPU
tox64
.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.
See Also
compiler.build.dotNETAssembly
| compiler.build.DotNETAssemblyOptions
| MathWorks.MATLAB.Types.RunOptions
Related Topics
- Deploy MATLAB Function to .NET Application Using MATLAB Data API for .NET
- Deploy MATLAB Classes to .NET Application Using MATLAB Data API for .NET
- Deploy MATLAB Function That Accepts Cell Array as Input Argument to .NET Application
- MATLAB Compiler SDK .NET Target Requirements
- Download and Install MATLAB Runtime
- Pass .NET Data Types to MATLAB Functions
- Handle MATLAB Data in .NET Applications