Main Content

Write C++ Functions Callable from MATLAB (MEX Files)

Create high-performance functions, implemented in modern C++, that can be called from MATLAB®

Use the C++ MEX API to create MATLAB functions that provide the efficiency of C++ programs and that can access external functions and libraries from MATLAB. The C++ MEX API provides these features:

  • Uses modern C++ programming features and object-oriented designs.

  • Calls MATLAB functions from the MEX function.

  • Integrates seamlessly into MATLAB, getting inputs from and returning results to MATLAB.

  • Supports MATLAB data types and copy-on-write semantics.

  • Writes thread-safe multi-threaded MEX functions.

  • Executes C++ MEX functions out-of-process.

Note

Functions in the MATLAB C++ APIs use the matlab::data::Array class defined in the MATLAB Data API for C++. If your MEX functions must run in MATLAB R2017b or earlier, or if you prefer to work in the C language, then use the C Matrix API, which works with the mxArray data structure instead. For more information, see Write C Functions Callable from MATLAB (MEX Files).

Build Function

mexBuild MEX function or engine application

C++ Classes

matlab::mex::FunctionBase class for C++ MEX functions
matlab::mex::ArgumentListContainer for inputs and outputs from C++ MEX functions

Out-of-Process Execution

mexhostCreate host process for C++ MEX function
fevalEvaluate C++ MEX function in MEX host process
matlab.mex.MexHostOut-of-process host for C++ MEX function execution

Topics

Create C++ MEX Functions

Setup and Build MEX Files

Design of C++ MEX Functions

MATLAB Data Types in MEX Functions

Call MATLAB Functions

Separate Threads and Processes

Access MATLAB Variables