Main Content

Generate a C++ MATLAB Data API Shared Library and Build a C++ Application

Supported platform: Windows®, Linux®, Mac

This example shows how to create a C++ shared library from a MATLAB® function. You can integrate the generated library into a C++ application. This example also shows how to call the C++ shared library from a C++ application. The target system does not require a licensed copy of MATLAB to run the application.

Create Functions in MATLAB

In MATLAB, examine the MATLAB code that you want packaged. For this example, open addmatrix.m located in matlabroot\extern\examples\compilersdk\c_cpp\matrix.

 addmatrix.m

At the MATLAB command prompt, enter:

addmatrix([1 4 7; 2 5 8; 3 6 9], [1 4 7; 2 5 8; 3 6 9])

The output is:

 ans =
     2     8    14
     4    10    16
     6    12    18

Create a C++ Shared Library Using Library Compiler App

  1. On the MATLAB Apps tab, on the far right of the Apps section, click the arrow. In Application Deployment, click Library Compiler.

    Alternatively, you can open the Library Compiler app from the MATLAB command prompt by entering:

    libraryCompiler

  2. In the Type section of the toolstrip, click C++ Shared Library.

    In the Library Compiler app project window, specify the files of the MATLAB application that you want to deploy.

    1. In the Exported Functions section of the toolstrip, click Add exported function to the project.

    2. In the Add Files window, browse to the example folder, and select the function you want to package. Click Open.

    The function is added to the list of exported function files. Repeat this step to package multiple files in the same application.

    For this example, navigate to matlabroot\extern\examples\compilersdk\c_cpp\matrix and select addmatrix.m.

  3. In the Packaging Options section of the toolstrip, decide whether to include the MATLAB Runtime installer in the generated application by selecting one of the options:

    • Runtime downloaded from web — Generate an installer that downloads the MATLAB Runtime and installs it along with the deployed MATLAB application. You can specify the file name of the installer.

    • Runtime included in package — Generate an application that includes the MATLAB Runtime installer. You can specify the file name of the installer.

      Note

      The first time you select this option, you are prompted to download the MATLAB Runtime installer.

Specify Shared Library Settings

  1. The Library Name field is automatically populated with addmatrix as the name of the packaged shared library. Rename it as libmatrix. The same name is followed through in the implementation of the shared library.

  2. In the Samples section, select Create New Sample, and click addmatrix.m.

    In the MATLAB file that opens, edit the code to initialize a1 to a nonzero value:

    a1 = [1 4 7; 2 5 8; 3 6 9]; % Initialize a1 here
    a2 = a1; % Initialize a2 here
    a = addmatrix(a1, a2);

    Save the file and return to the Library Compiler app. For more information and limitations, see Sample Driver File Creation.

  3. Select the type of API for the generated C++ shared libraries. In the API selection section at the bottom, select Create interface that uses the MATLAB Data API. For more information, see API Selection for C++ Shared Library.

Customize the Application and Its Appearance

In the Library Compiler app, you can customize the installer, customize your application, and add more information about the application.

  • Library information — Information about the deployed application. You can also customize the appearance of the application by changing the application icon and splash screen. The generated installer uses this information to populate the installed application metadata. See Customize the Installer.

  • Additional installer options — Default installation path for the generated installer and custom logo selection. See Change the Installation Path.

  • Files required for your library to run — Additional files required by the generated application to run. These files are included in the generated application installer. See Manage Required Files in Compiler Project.

  • Files installed for your end user — Files that are installed with your application.

    See Specify Files to Install with Application.

Package the Application

When you are finished selecting your packaging options, save your Library Compiler project and generate the packaged application.

  1. Click Package.

    In the Save Project dialog box, specify the location to save the project.

  2. In the Package dialog box, verify that Open output folder when process completes is selected.

    When the packaging process is complete, examine the generated output in the target folder.

    • Three folders are generated: for_redistribution, for_redistribution_files_only, and for_testing.

      For more information about the files generated in these folders, see Files Generated After Packaging MATLAB Functions.

    • The log file PackagingLog.html contains packaging results.

Create C++ Shared Library Using compiler.build.cppSharedLibrary

As an alternative to the Library Compiler app, you can create a C++ shared library using a programmatic approach. If you have already created a library using the Library Compiler, see Implement C++ MATLAB Data API Shared Library with Sample Application.

  1. Save the path to the addmatrix.m file located in matlabroot\extern\examples\compilersdk\c_cpp\matrix.

    appFile = fullfile(matlabroot,'extern','examples','compilersdk','c_cpp','matrix','addmatrix.m');
  2. Save the following code in a sample file named addmatrixSample1.m:

    a1 = [1 4 7; 2 5 8; 3 6 9];
    a2 = a1;
    a = addmatrix(a1, a2);

  3. Build the C++ shared library using the compiler.build.cppSharedLibrary function. Use name-value arguments to specify the library name and add a sample file.

    buildResults = compiler.build.cppSharedLibrary(appFile, ...
    'LibraryName','libmatrix', ...
    'SampleGenerationFiles','addmatrixSample1.m');

    You can specify additional options in the compiler.build command by using name-value arguments. For details, see compiler.build.cppSharedLibrary.

    The compiler.build.Results object buildResults contains information on the build type, generated files, included support packages, and build options.

  4. This syntax generates the following files within a folder named libmatrixcppSharedLibrary in your current working directory:

    • samples\addmatrixSample1_mda.cpp — C++ sample driver file.

    • v2\generic_interface\libmatrix.ctf — Component technology file that contains the deployable archive.

    • v2\generic_interface\readme.txt — Text file that contains packaging information.

    • GettingStarted.html — HTML file that contains information on integrating your shared library.

    • includedSupportPackages.txt — Text file that lists all support files included in the library.

    • mccExcludedFiles.log — Log file that contains a list of any toolbox functions that were not included in the application. For information on non-supported functions, see MATLAB Compiler Limitations.

    • readme.txt — Text file that contains packaging and interface information.

    • requiredMCRProducts.txt — Text file that contains product IDs of products required by MATLAB Runtime to run the application.

    • unresolvedSymbols.txt — Text file that contains information on unresolved symbols.

    Note

    The generated library does not include MATLAB Runtime or an installer. To create an installer using the buildResults object, see compiler.package.installer.

Implement C++ MATLAB Data API Shared Library with Sample Application

After packaging your C++ shared libraries, you can call them from a C++ application. The C++ application that you create uses the sample C++ driver code generated during packaging. The sample C++ code calls the C++ shared libraries, and it is based on the sample MATLAB file you created in previous setup steps.

These steps are also explained in the GettingStarted.html file. Before starting, make sure that you Install and Configure MATLAB Runtime and that you have a C++ compiler installed.

  1. Copy and paste the generated C++ driver code file addmatrixSample1_mda.cpp from the samples folder into the v2\generic_interface folder that contains the file libmatrix.ctf.

    The program listing for addmatrixSample1_mda.cpp is shown below.

    /*=================================================================
     *
     * ADDMATRIXSAMPLE1
     * Sample driver code that uses the generic interface and
     * MATLAB Data API to call a C++ shared library created using 
     * MATLAB Compiler SDK.
     * Refer to the MATLAB Compiler SDK documentation for more
     * information.
     *
     *=================================================================*/
    
    // Include the header file required to use the generic
    // interface for the C++ shared library generated by the
    // MATLAB Compiler SDK.
    #include "MatlabCppSharedLib.hpp"
    #include <iostream>
    
    namespace mc = matlab::cpplib;
    namespace md = matlab::data;
    
    std::shared_ptr<mc::MATLABApplication> setup()
    {
    	auto mode = mc::MATLABApplicationMode::IN_PROCESS;
    	// Specify MATLAB startup options
    	std::vector<std::u16string> options = {};
    	std::shared_ptr<mc::MATLABApplication> matlabApplication = mc::initMATLABApplication(mode, options);
    	return matlabApplication;
    }
    
    int mainFunc(std::shared_ptr<mc::MATLABApplication> app, const int argc, const char * argv[])
    {		
    	md::ArrayFactory factory;
    	md::TypedArray<double> a1In = factory.createArray<double>({3, 3}, {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0});
    	md::TypedArray<double> a2In = factory.createArray<double>({3, 3}, {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0});
    	try {
    		// The path to the CTF (library archive file) passed to 
    		// initMATLABLibrary or initMATLABLibraryAsync may be either absolute
    		// or relative. If it is relative, the following will be prepended
    		// to it, in turn, in order to find the CTF:
    		// - the directory named by the environment variable 
    		// CPPSHARED_BASE_CTF_PATH, if defined
    		// - the working directory
    		// - the directory where the executable is located
    		// - on Mac, the directory three levels above the directory
    		// where the executable is located
    		
    		// If the CTF is not in one of these locations, do one of the following:
    		// - copy the CTF
    		// - move the CTF
    		// - change the working directory ("cd") to the location of the CTF
    		// - set the environment variable to the location of the CTF
    		// - edit the code to change the path
    		auto lib = mc::initMATLABLibrary(app, u"libmatrix.ctf");
    		std::vector<md::Array> inputs{a1In, a2In};
    		auto result = lib->feval(u"addmatrix", 1, inputs);
    	} catch (const std::exception & exc) {
    		std::cerr << exc.what() << std::endl;
    		return -1;
    	}
    	return 0;
    }
    
    // The main routine. On the Mac, the main thread runs the system code, and
    // user code must be processed by a secondary thread. On other platforms, 
    // the main thread runs both the system code and the user code.
    int main(const int argc, const char * argv[]) 
    {
    	int ret = 0;
    	try {
    		auto matlabApplication = setup();
    		ret = mc::runMain(mainFunc, std::move(matlabApplication), argc, argv);
    		// Calling reset() on matlabApplication allows the user to control
    		// when it is destroyed, which automatically cleans up its resources.
    		// Here, the object would go out of scope and be destroyed at the end 
    		// of the block anyway, even if reset() were not called.
    		// Whether the matlabApplication object is explicitly or implicitly
    		// destroyed, initMATLABApplication() cannot be called again within
    		// the same process.
    		matlabApplication.reset();
    	} catch(const std::exception & exc) {
    		std::cerr << exc.what() << std::endl;
    		return -1;
    	}
    	return ret;
    }
  2. At the system command prompt, navigate to the generic_interface folder where you copied addmatrixSample1_mda.cpp.

  3. Compile and link the application using mbuild at the system command prompt.

    mbuild addmatrixSample1_mda.cpp
  4. Run the application from the system command prompt.

    addmatrixSample1_mda.exe

    The generated C++ code does not display any output.

Note

For an example on how to retrieve and display a struct array, a cell array, or a character vector from an feval call, see the files subtractmatrix.m and subtractmatrix_mda.cpp located in matlabroot\extern\examples\compilersdk\c_cpp\matrix.

See Also

| | |

Related Topics