This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

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.

  • 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 of 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 of how to create a C++ MEX source file. 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