User`s manual

C MEX-Files
2-3
C MEX-Files
C MEX-files are built by using the mex script to compile your C source code with
additional calls to API routines.
The Components of a C MEX-File
The source code for a MEX-file consists of two distinct parts:
A computational routine that contains the code for performing the
computations that you want implemented in the MEX-file. Computations
can be numerical computations as well as inputting and outputting data.
A gateway routine that interfaces the computational routine with MATLAB
by the entry point
mexFunction and its parameters prhs, nrhs, plhs, nlhs,
where
prhs is an array of right-hand input arguments, nrhs is the number
of right-hand input arguments,
plhs is an array of left-hand output
arguments, and
nlhs is the number of left-hand output arguments. The
gateway calls the computational routine as a subroutine.
In the gateway routine, you can access the data in the
mxArray structure and
then manipulate this data in your C computational subroutine. For example,
the expression
mxGetPr(prhs[0]) returns a pointer of type double * to the real
data in the
mxArray pointed to by prhs[0]. You can then use this pointer like
any other pointer of type
double * in C. After calling your C computational
routine from the gateway, you can set a pointer of type
mxArray to the data it
returns. MATLAB is then able to recognize the output from your computational
routine as the output from the MEX-file.
The following C MEX Cycle figure shows how inputs enter a MEX-file, what
functions the gateway routine performs, and how outputs return to MATLAB.