The C calling sequence for mexFunction is well-defined and is the same for all mex functions. It is general enough to work with MATLAB functions requiring any number of input and output arguments. The mexFunction must return void, and it takes exactly four arguments: nlhs, plhs, nrhs, and prhs are traditional names, though these variables may actually be given any name desired by the user.

File: HelloWorld.c

#include 
#include "mex.h"

void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
    printf("Hello World\n");
}

'nlhs' and 'nrhs' (lines 4-5) are integer variables which, on calling mexFunction, contain the number of left-hand or right-hand side arguments passed to the function from MATLAB. Note that nlhs and nrhs are variables since MATLAB functions can be called with any number of input arguments and be asked to return any number of variables. It's up to the programmer of the mex function to ensure that invalid calling sequences (e.g. too many input arguments) are handled elegantly, otherwise a segfault in the mex function may cause the MATLAB interpreter process to crash as well.

'plhs' and 'prhs' (lines 4-5) are pointers to arrays of mxArray objects. plhs is of length nlhs and prhs must be of length nrhs on exiting mexFunction. The mxArray data type hides the complexity of MATLAB's opaque data types and there is a well-defined API for moving data from the mxArray objects into a format which can be understood by C. We will discuss this API in more detail later in the topic; for now our mexFunction simply prints "Hello World" and then returns, not making use of any of the input or output arguments.

 
©   Cornell University  |  Center for Advanced Computing  |  Copyright Statement  |  Inclusivity Statement