Clear Filters
Clear Filters

Communicating to NET dll by class.

18 views (last 30 days)
Hi,
Is there anyway to send a class to and from a matlab .NET dll and a C# Visual studio project?
Thanks in advance
Laurent

Accepted Answer

Yash Sharma
Yash Sharma on 17 Jan 2024
Hi Laurent,
Yes, it is possible to send a class to and from a MATLAB .NET assembly and a C# Visual Studio project. MATLAB Compiler SDK allows you to create a .NET assembly from MATLAB code, which can then be used in .NET applications such as those written in C#. However, there are some considerations and steps you need to follow:
Creating a .NET Assembly from MATLAB
  1. Write your MATLAB code and save it in a function or class that you want to compile into a .NET assembly.
  2. Use the MATLAB Compiler SDK to compile your MATLAB code into a .NET assembly. You can use the deploytool or the mcc command to do this. For example:
mcc -W 'dotnet:MyMatlabAssembly,ClassLibrary,4.0,private' -T 'link:lib' -d 'C:\MyMatlabAssembly' -v 'class{MyClass:C:\MyMatlabCode\myFunction.m}'
This command will generate a .NET assembly MyMatlabAssembly.dll that contains the class MyClass with the method myFunction.
Using the .NET Assembly in a C# Visual Studio Project
  1. Add a reference to the generated MATLAB .NET assembly (MyMatlabAssembly.dll) in your C# project.
  2. Add a reference to the MWArray.dll assembly, which is provided by MATLAB Compiler Runtime (MCR) and is necessary for handling MATLAB data types in .NET.
  3. Use the MATLAB class in your C# code. You will need to create instances of MWArray or its derived classes (e.g., MWNumericArray, MWStructArray, etc.) when interacting with the MATLAB functions or classes.
using MathWorks.MATLAB.NET.Arrays;
using MyMatlabAssembly;
class Program
{
static void Main(string[] args)
{
// Initialize MATLAB Runtime
MWArray[] inputs = new MWArray[] { /* your input data as MWArray */ };
MyClass matlabClass = new MyClass();
// Call MATLAB function
MWArray result = matlabClass.myFunction(inputs);
// Convert result to a C# data type if needed
// ...
// Clean up
matlabClass.Dispose();
}
}
If you have a custom class in C# that you want to pass to MATLAB, or vice versa, you will typically need to convert the class to a compatible MWArray type (e.g., MWStructArray for MATLAB structs) before calling the MATLAB function and then convert it back to your custom class after receiving the output.
Take a look at the below documentaion which might be helpful for your implementaion.
Hope this helps!

More Answers (1)

Laurent Davenne
Laurent Davenne on 17 Jan 2024
Thank you Yash!

Tags

Products


Release

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!