Main Content

Create C++ Header File from Strongly Typed MATLAB Function

This example shows how to create a C++ header file from a strongly typed MATLAB® function and integrate it with sample C++ application code.

Create Function in MATLAB

Create a strongly typed MATLAB function in a file named stronglyTypedFactorial.m with this 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++ Header File

Generate the C++ header file.

0 class(es) and 1 function(s) written to myFactorial.hpp

The function creates the myFactorial.hpp header file that defines a C++ data array accepting an argument n 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.

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

The interface verifies that the input meets the mustBeReal argument. At run-time, the MATLAB stronglyTypedFactorial function verifies that the input meets the mustBeLessThan(n,22) argument. For more information, see Data Type Mappings Between C++ and Strongly Typed MATLAB Code.


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

Create a C++ application code file named factApp.cpp with this code. When writing your C++ application, you must include:

  • MatlabEngine.hpp before any generated header files

  • myFactorial.hpp generated by the matlab.engine.typedinterface.generateCPP function


Verify that you have selected a supported C++ compiler.

mex -setup -client engine C++

Compile and link the C++ application at the MATLAB command prompt. For more information, see Requirements to Build C++ Engine Programs.

mex -client engine factApp.cpp

Determine the run-time library path. For an example built on Windows®, type:

rtpath = fullfile(matlabroot,"extern","bin","win64")

Set the run-time library path from the system prompt, substituting the value for rtpath. For example:

set PATH=C:\Program Files\MATLAB\R2022a\extern\bin\win64;%PATH%

Run the application.

Factorial of 5 is 120

See Also

| |

Related Topics