Main Content

Create C++ MATLAB Data API Shared Library Header from Strongly Typed MATLAB Function

This example shows how to create a C++ MATLAB® Data API shared library header from a strongly typed MATLAB function and integrate it with sample C++ application code. The target system does not require a licensed copy of MATLAB to run the application.


  • Start this example by creating a new work folder that is visible to the MATLAB search path.

  • Verify that you have a C++ compiler installed by typing mbuild -setup at the MATLAB command prompt.

  • End users must have an installation of MATLAB Runtime to run the application. For details, see Install and Configure MATLAB Runtime.

    For testing purposes, you can use an installation of MATLAB instead of MATLAB Runtime.

Create Function in MATLAB

Create a MATLAB file named stronglyTypedFactorial.m with the following code:

function fact = stronglyTypedFactorial(n)
    n (1,1) uint64 {mustBeReal, mustBeLessThan(n,22)}
fact = 1;
for i = 1:n
    fact = fact*i;

Test the function at the MATLAB command prompt.

ans =

Generate C++ Shared Library Header Using the mcc Command

Generate the C++ shared library header using the mcc command. At the command prompt, type:

if ~exist('output/cpp','dir')
    mkdir output/cpp
mcc -W 'cpplib:stronglyTypedFactorial,generic' stronglyTypedFactorial.m -d output/cpp
The following files are created in the v2 > generic_interface folder:

  • readme.txt

  • stronglyTypedFactorial.ctf

  • stronglyTypedFactorialv2.hpp

The stronglyTypedFactorialv2.hpp header file contains a C++ data array that accepts an argument of type uint64_t.

matlab::data::Array stronglyTypedFactorial(std::shared_ptr<MATLABControllerType> _matlabPtr, uint64_t n)

This uint64_t mapping matches the strongly typed uint64 data type of the MATLAB argument.

n (1,1) uint64 {mustBeReal, mustBeLessThan(n,22)}

For details, see Data Type Mappings Between C++ and Strongly Typed MATLAB Code.


Integrate C++ MATLAB Data API Shared Library Header with C++ Application

Create a C++ application code file named factApp.cpp with the following code.



When writing C++ application code, you must include the header file (.hpp file) generated by the mcc command or the Library Compiler app and the MatlabCppSharedLib.hpp header file using #include directives.

Compile and link the C++ application at the MATLAB command prompt.

mbuild factApp.cpp -outdir output/cpp

Run the application from the system command prompt by passing the deployable archive (.ctf file) as an input. For testing purposes, you can run the application from the MATLAB command prompt.

!output\cpp\factApp.exe output\cpp\v2\generic_interface\stronglyTypedFactorial.ctf
Factorial of 5 is 120

See Also


Related Topics