External Interfaces/API    

A First Example -- Passing a Scalar

Let's look at a simple example of C code and its MEX-file equivalent. Here is a C computational function that takes a scalar and doubles it.

Below is the same function written in the MEX-file format.

In C, function argument checking is done at compile time. In MATLAB, you can pass any number or type of arguments to your M-function, which is responsible for argument checking. This is also true for MEX-files. Your program must safely handle any number of input or output arguments of any supported type.

To compile and link this example source file at the MATLAB prompt, type

This carries out the necessary steps to create the MEX-file called timestwo with an extension corresponding to the platform on which you're running. You can now call timestwo as if it were an M-function.

You can create and compile MEX-files in MATLAB or at your operating system's prompt. MATLAB uses mex.m, an M-file version of the mex script, and your operating system uses mex.bat on Windows and mex.sh on UNIX. In either case, typing

at the prompt produces a compiled version of your MEX-file.

In the above example, scalars are viewed as 1-by-1 matrices. Alternatively, you can use a special API function called mxGetScalar that returns the values of scalars instead of pointers to copies of scalar variables. This is the alternative code (error checking has been omitted for brevity).

This example passes the input scalar x by value into the timestwo_alt subroutine, but passes the output scalar y by reference.


  Examples of C MEX-Files Passing Strings