Build and Load .NET Assembly for MATLAB
To access .NET libraries and other functionality from C# files, build a .NET assembly using a C# development tool like Microsoft® Visual Studio® and then load the assembly into MATLAB®. MATLAB provides sample C# code files that you can use to experiment with .NET functionality from within MATLAB. You can access those files in this folder:
fullfile(matlabroot,"extern","examples","NET","NetSample")
From your development tool, open a new project and create a C# class library.
Copy the C# files that contain classes and other constructs into your project. For example, copy the sample
NetDocCell.csfile into your project.Build the project as a
.dllshared library file. If you need detailed instructions for building the library file, consult your development tool documentation.Make note of the default .NET runtime environment used to build the project. By default, MATLAB loads assemblies using .NET Framework on Windows®, while a project in Visual Studio defaults to .NET Core. To change the .NET runtime environment in MATLAB to match the project environment, type:
e = dotnetenv("core")On macOS and Linux® platforms, MATLAB loads assemblies using .NET Core.
Load the assembly into MATLAB using the
NET.addAssemblyfunction. Because the assembly is private, specify the full path to the library file. For example, these commands load theNetDocCell.dllfile from theC:\workfolder.asmPath = fullfile("C:","work","NetDocCell.dll"); NET.addAssembly(asmPath);
After you load the .NET assembly into MATLAB, you can use its functionality. To call
functions from the .NET assembly in MATLAB, use the name of the assembly as the namespace. For example, call the .NET
function MyGraph.getNewData:
mlData = NetDocCell.MyGraph.getNewData;
If you load a .NET Core assembly and
then modify and rebuild it, first call the NET.unloadAssembly function. (since R2026a) Then call
NET.addAssembly to reload it. If you modify and rebuild a .NET
Framework assembly, you must restart MATLAB to access the new code.
See Also
dotnetenv | NET.addAssembly | NET.unloadAssembly