Main Content

Integrate a .NET Assembly Into a C# Application

This example shows how to call a .NET assembly from a C# application. To create the .NET assembly from your MATLAB® function, see Generate a .NET Assembly and Build a .NET Application.

  1. Install the .NET assembly from the for_redistribution folder.

    The generated shared libraries and support files are located in the for_testing folder.

  2. Open Microsoft® Visual Studio® and create a project. For this example, create a C# Console Application called MainApp and create a reference to your assembly file MagicSquareComp.dll.

    Ensure that the assembly is located in the application folder created where you installed the component.

  3. Create a reference to the MWArray API. The location of the API within MATLAB Runtime is:

    matlabrootMATLAB Runtime\v##\toolbox\dotnetbuilder\bin\arch\version\MWArray.dll

  4. Go to Build > Configuration Manager and change the platform from Any CPU to x64.

  5. Copy the following C# code into the project and save it.

     C# Code to Implement Application

  6. After you finish writing your code, build and run it with Microsoft Visual Studio.


When calling your component, you can take advantage of implicit conversion from .NET types to MATLAB types, by passing the native C# value directly to makeSqr:

input = 5;
obj.makesquare(1, input);

You can also use explicit conversion:

input = new MWNumericArray(5);
obj.makesquare(1, input);

Running the Component Installer

The compiler creates an installer for the generated .NET component. After compilation is complete, you can find this installer in the for_redistribution folder in your project folder. By default, the compiler names the installer MyAppInstaller_web.exe or MyAppInstaller_mcr.exe, depending on which packaging option you chose. Using the Application Information area of the Library Compiler app, you can customize the look of the installer.

For example, when an end user double-clicks the component installer, the first screen identifies your component by name and version number.

By clicking Next on each screen, the installer leads you through the installation process. During installation, you can specify the installation folder. The installer also automatically downloads the MATLAB Runtime, if needed.