Main Content

mexFunction (C)

Entry point to C/C++ MEX function built with C Matrix API

C Syntax

#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, 
  const mxArray *prhs[])

Description

Note

To write MEX functions using modern C++ features and the MATLAB Data API, see C++ MEX Applications.

mexFunction is not a routine you call. Rather, mexFunction is the name of the gateway function in C which every MEX function requires. When you invoke a MEX function, MATLAB® finds and loads the corresponding MEX function of the same name. MATLAB then searches for a symbol named mexFunction within the MEX function. If it finds one, it calls the MEX function using the address of the mexFunction symbol. MATLAB displays an error message if it cannot find a routine named mexFunction inside the MEX function.

When you invoke a MEX function, MATLAB automatically seeds nlhs, plhs, nrhs, and prhs with the calling arguments. In the syntax of the MATLAB language, functions have the general form:

[a,b,c,...] = fun(d,e,f,...)

where the ... denotes more items of the same format. The a,b,c... are left-side output arguments, and the d,e,f... are right-side input arguments. The arguments nlhs and nrhs contain the number of left side and right side arguments, respectively. prhs is an array of mxArray pointers whose length is nrhs. plhs is an array whose length is nlhs, where your function must set pointers for the output mxArrays.

Note

It is possible to return an output value even if nlhs = 0, which corresponds to returning the result in the ans variable.

To experiment with passing input arguments, build the mexfunction.c example, following the instructions in Tables of MEX Function Source Code Examples.

Input Arguments

expand all

Number of expected mxArray output arguments, specified as an integer.

Array of pointers to the expected mxArray output arguments.

Number of input mxArrays, specified as an integer.

Array of pointers to the mxArray input arguments. Do not modify any prhs values in your MEX file. Changing the data in these read-only mxArrays can produce undesired side effects.

Examples

See these examples in matlabroot/extern/examples/mex:

Introduced before R2006a