External Interfaces/API    

Creating C Language MEX-Files


This chapter describes how to write MEX-files in the C programming language. It discusses the MEX-file itself, how these C language files interact with MATLAB, how to pass and manipulate arguments of different data types, how to debug your MEX-file programs, and several other, more advanced topics.

The following list summarizes the contents of this chapter:

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:

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.

Figure 2-1: C MEX Cycle


 Technical Support Required Arguments to a MEX-File