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 MATLAB function named stronglyTypedFactorial.m
with this
code:
function fact = stronglyTypedFactorial(n) arguments n (1,1) uint64 {mustBeReal, mustBeLessThan(n,22)} end fact = 1; for i = 1:n fact = fact*i; end end
Test the function at the MATLAB command prompt.
stronglyTypedFactorial(5)
ans = uint64 120
Generate C++ Header File
Generate the C++ header file:
matlab.engine.typedinterface.generateCPP("myFactorial.hpp",Functions="stronglyTypedFactorial")
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 runtime, 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.The
myFactorial.hpp
file generated by thematlab.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 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.
factApp.exe
Factorial of 5 is 120
See Also
matlab.engine.typedinterface.generateCPP
| arguments
| properties