Generate a C++ MATLAB Data API Shared Library and Build a C++ Application - MATLAB & Simulink (original) (raw)

Main Content

Supported platform: Windows®, Linux®, Mac

This example shows how to create a C++ shared library from MATLAB® functions. 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

  1. In MATLAB, examine the MATLAB code that you want to package.
    Copy the matrix folder that ships with MATLAB to your work folder.
    copyfile(fullfile(matlabroot,'extern','examples','compilersdk','c_cpp','matrix'),'matrix')
    Navigate to the new matrix subfolder in your work folder.
  2. Examine and test the functions addmatrix.m,multiplymatrix.m, andeigmatrix.m.

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

Build a C++ shared library using a programmatic approach. Alternatively, if you want to create a C++ shared library using a graphical interface, see Package MATLAB Function Using C++ Shared Library Compiler App with MATLAB Data API.

  1. Save the list of function files in a cell array.
    functionfiles = {'addmatrix.m', 'multiplymatrix.m', 'eigmatrix.m'}
  2. Create MATLAB sample code that calls the functions. Sample files are used to generate a sample application in the target language. For more information and limitations, see Create Sample Code to Call Exported Function.
    Save the following code in a sample file namedlibmatrixSample.m:
    % Sample script to demonstrate execution of functions
    % addmatrix, eigmatrix, and multiplymatrix
    a1 = [1 4 7; 2 5 8; 3 6 9]; % Initialize a1 here
    a2 = a1; % Initialize a2 here
    a = addmatrix(a1, a2);
    e = eigmatrix(a1);
    m = multiplymatrix(a1, a2);
    You may instead choose to not include a sample driver file at all during the packaging step. If you create your own C++ application code, you can move it to the appropriate directory and compile it usingmbuild after the MATLAB functions are packaged.
  3. Build the C++ shared library using thecompiler.build.cppSharedLibrary function. Use name-value arguments to specify the library name and add the sample file.
    buildResults = compiler.build.cppSharedLibrary(functionfiles,...
    'LibraryName','libmatrix',...
    'SampleGenerationFiles','libmatrixSample.m');
    You can specify additional options in thecompiler.build command by using name-value arguments. For details, see compiler.build.cppSharedLibrary.
    The compiler.build.Results objectbuildResults contains information on the build type, generated files, included support packages, and build options.
  4. This syntax generates the following files within a folder namedlibmatrixcppSharedLibrary in your current working directory:
    • samples\libmatrixSample1_mda.cpp — C++ sample application that calls theaddmatrix function.
    • samples\libmatrixSample2_mda.cpp — C++ sample application that calls theeigmatrix function.
    • samples\libmatrixSample3_mda.cpp — C++ sample application that calls themultiplymatrix function.
    • 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 thebuildResults object, see compiler.package.installer.

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

Note

To call the library using a more advanced application that calls all three functions and handles errors, use the C++ applicationmatrix_mda.cpp located in the folder

matlabroot\extern\examples\compilersdk\c_cpp\matrix

For more details, see Integrate C++ Shared Libraries with MATLAB Data API.

Before starting, make sure that you Download and Install MATLAB Runtime and that you have a C++ compiler installed.

After packaging C++ shared libraries, you can call them from a C++ application. The C++ code generated in the samples folder is based on the sample MATLAB file you created.

  1. Copy and paste the generated file libmatrix.ctf from the v2\generic_interface folder into thesamples folder that containslibmatrixSample1_mda.cpp.
    The program listing for libmatrixSample1_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;  
}  
  1. At the MATLAB command prompt or your system command prompt, navigate to thesamples folder where you copiedlibmatrix.ctf.
  2. Compile and link the application using mbuild at the system command prompt.
    mbuild libmatrixSample1_mda.cpp
  3. Run the application from the system command prompt.
    By default, the generated C++ code does not display any output.
  4. (Optional) Compile and link the other sample C++ applications usingmbuild. You can also use the generated C++ code as a guide to create your own application.
    For further details, see Integrate C++ Shared Libraries with MATLAB Data API.

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 filessubtractmatrix.m andsubtractmatrix_mda.cpp located in_`matlabroot`_\extern\examples\compilersdk\c_cpp\matrix.

See Also

compiler.build.cppSharedLibrary | mcc

Topics