Contenido principal

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")
  1. From your development tool, open a new project and create a C# class library.

  2. Copy the C# files that contain classes and other constructs into your project. For example, copy the sample NetDocCell.cs file into your project.

  3. Build the project as a .dll shared library file. If you need detailed instructions for building the library file, consult your development tool documentation.

  4. 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.

  5. Load the assembly into MATLAB using the NET.addAssembly function. Because the assembly is private, specify the full path to the library file. For example, these commands load the NetDocCell.dll file from the C:\work folder.

    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

| |

Topics