Documentation

This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English verison of the page.

Note: This page has been translated by MathWorks. Please click here
To view all translated materals including this page, select Japan from the country navigator on the bottom of this page.

Creating C++ MEX Files

MEX files support all C++ language standards. This topic discusses specific C++ language issues to consider when creating and using MEX files.

Use the C syntax statements in the MATLAB® API libraries in your C++ applications. You can also copy MATLAB C code examples into C++ applications. For example, see the mexcpp.cpp file that contains both C and C++ statements.

Creating Your C++ Source File

The C++ source code for the examples provided by MATLAB use the .cpp file extension. The extension .cpp is unambiguous and recognized by C++ compilers. Other possible extensions include .C, .cc, and .cxx.

Compiling and Linking

To build a C++ MEX file, type:

mex filename.cpp

where filename is the name of the source file.

You can run a C++ MEX file only on systems with the same version of MATLAB that the file was compiled on.

Memory Considerations for Class Destructors

Do not use the mxFree or mxDestroyArray functions in a C++ destructor of a class used in a MEX-function. If the MEX-function throws an error, MATLAB cleans up MEX-file variables, as described in Automatic Cleanup of Temporary Arrays.

If an error occurs that causes the object to go out of scope, MATLAB calls the C++ destructor. Freeing memory directly in the destructor means both MATLAB and the destructor free the same memory, which can corrupt memory.

Use mexPrintf to Print to MATLAB Command Window

Using cout or the C-language printf function does not work as expected in C++ MEX files. Use the mexPrintf function instead.

See Also

Related Examples

More About

Was this topic helpful?