Main Content

C++ MEX Functions

MEX or MATLAB executable refers to programs that are automatically loaded and can be called like any MATLAB® function.


C++ MEX functions are based on two C++ APIs:

  • The MATLAB Data API supports MATLAB data types and optimizations like copy-on-write for data arrays passed to MEX functions. For more information, see MATLAB Data API for C++.

  • A subset of the MATLAB C++ Engine API supports calling MATLAB functions, execution of statements in the MATLAB workspace, and access to variables and objects. For more information, see C++ MEX API.

The C++ MEX API supports C++11 features and is not compatible with the C MEX API. You cannot mix these APIs in a MEX file.

Basic Design of C++ MEX Functions

A C++ MEX function is implemented as a class named MexFunction that inherits from matlab::mex::Function. The MexFunction class overrides the function call operator, operator(). This implementation creates a function object that you can call like a function.

Calling the MEX function from MATLAB instantiates the function object, which maintains its state across subsequent calls to the same MEX function.

Here is the basic design of a C++ MEX function. It is a subclass of matlab::mex::Function that must be named MexFunction. The MexFunction class overrides the function call operator, operator().

#include "mex.hpp"
#include "mexAdapter.hpp"

class MexFunction : public matlab::mex::Function {
    void operator()(matlab::mex::ArgumentList outputs, matlab::mex::ArgumentList inputs) {
        // Function implementation

Inputs and outputs to the MEX function are passed as elements in a matlab::mex::ArgumentList. Each input or output argument is a matlab::data::Array contained in the matlab::mex::ArgumentList.

For an example, see Create a C++ MEX Source File.

Call MEX Function from MATLAB

To call a MEX function, use the name of the file, without the file extension. The calling syntax depends on the input and output arguments defined by the MEX function. The MEX file must be on the MATLAB path or in the current working folder when called.

Examples of C++ MEX Functions

These examples illustrate the implementation of C++ MEX Functions:

Related Topics