Main Content

Generate a C++ mwArray API Shared Library and Build a C++ Application

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.

Create Functions in MATLAB

  1. In MATLAB, examine the MATLAB code that you want packaged.

    For this example, 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, and eigmatrix.m.

  3. 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 named libmatrixSample.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 using mbuild after the MATLAB functions are packaged.

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 mwArray API.

  1. Save the list of function files in a cell array.

    functionfiles = {'addmatrix.m', 'multiplymatrix.m', 'eigmatrix.m'}
  2. Build the C++ shared library using the compiler.build.cppSharedLibrary function. Use name-value arguments to add the sample file and specify the library name and interface API.

    buildResults = compiler.build.cppSharedLibrary(functionfiles,...
    'LibraryName','libmatrix',...
    'Interface','mwarray',...
    'SampleGenerationFiles','libmatrixSample.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.

    The function generates the following files within a folder named libmatrixcppSharedLibrary in your current working directory:

    • samples\libmatrixSample1_mwarray.cpp — C++ sample application that calls the addmatrix function.

    • samples\libmatrixSample2_mwarray.cpp — C++ sample application that calls the eigmatrix function.

    • samples\libmatrixSample3_mwarray.cpp — C++ sample application that calls the multiplymatrix function.

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

    • libmatrix.cpp — C++ source code file.

    • libmatrix.def — Module-definition file that provides the linker with module information.

    • libmatrix.dll — Dynamic-link library file.

    • libmatrix.exports — Exports file that contains all nonstatic function names.

    • libmatrix.h — C++ header file.

    • libmatrix.lib — Import library file.

    • 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 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++ mwArray API Shared Library with C++ Sample Application

Note

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

matlabroot\extern\examples\compilersdk\c_cpp\matrix
For more details, see Integrate C++ Shared Libraries with mwArray.

Before starting, make sure that you have a C++ compiler installed.

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

  1. Copy and paste the generated C++ code file libmatrixSample1_mwarray.cpp from the samples folder into the folder that contains libmatrix.lib.

    The program listing for libmatrixSample1_mwarray.cpp is shown below.

    /*=================================================================
     *
     * LIBMATRIXSAMPLE1
     * CPP Sample driver code for libmatrix that calls a shared library
     * created using MATLAB Compiler SDK.
     * Refer to the MATLAB Compiler SDK documentation for more information.
     *
     *=================================================================*/
    // Include the library specific header file as generated by the 
    // MATLAB Compiler
    #include <iostream>
    #include "libmatrix.h"
    
    void addmatrixSample() {
        try {
            mxDouble a1InData[] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0};
            mwArray a1In(3, 3, mxDOUBLE_CLASS);
            a1In.SetData(a1InData, 9);
            mxDouble a2InData[] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0};
            mwArray a2In(3, 3, mxDOUBLE_CLASS);
            a2In.SetData(a2InData, 9);
            mwArray aOut;
            addmatrix(1, aOut, a1In, a2In);
            std::cout << aOut << '\n';
        } catch (const mwException& e) {
            std::cerr << e.what() << std::endl;
        } catch (...) {
            std::cerr << "Unexpected error thrown" << std::endl;
        }
    }
    
    int run_main(int argc, const char** argv) {
        if (!libmatrixInitialize()) {
            std::cerr << "Could not initialize the library properly" << std::endl;
            return 2;
        } else {
            addmatrixSample();
            // Call the application and library termination routine
            libmatrixTerminate();
        }
        // Note that you should call mclTerminateApplication at the end of
        // your application to shut down all MATLAB Runtime instances.
        mclTerminateApplication();
        return 0;
    }
    
    // The main routine. On macOS, 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(int argc, const char** argv) {
        /* Call the mclInitializeApplication routine. Make sure that the application
         * was initialized properly by checking the return status. This initialization
         * has to be done before calling any MATLAB APIs or MATLAB Compiler SDK
         * generated shared library functions.
         */
        if (!mclInitializeApplication(nullptr, 0)) {
            std::cerr << "Could not initialize the application." << std::endl;
            return 1;
        }
        return mclRunMain(static_cast<mclMainFcnType>(run_main), argc, argv);
    }
    
  2. At the system command prompt, navigate to the folder where you copied libmatrixSample1_mwarray.cpp.

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

    mbuild libmatrixSample1_mwarray.cpp libmatrix.lib

    Note

    The .lib extension is used on Windows. On macOS, the file extension is .dylib, and on Linux it is .so.

  4. From the system command prompt, run the application. If you used sample MATLAB code in the packaging steps, the sample C++ application returns the same output as the MATLAB code.

    libmatrixSample1_mwarray.exe
    2 8 14
    4 10 16
    6 12 18
    
  5. (Optional) Compile and link the other sample C++ applications using mbuild. 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 mwArray.

See Also

|

Topics