Documentation Center

  • Trial Software
  • Product Updates

Use C++ Features in MEX-Files

C++ Class in MEX-Files

This example, mexcpp.cpp, illustrates how to use C++ code with your C language MEX-file. It uses member functions, constructors, destructors, and the iostream include file. To see the example, open the fileopen the file in MATLAB® Editor.

To build this example, at the command prompt type:

mex mexcpp.cpp

The calling syntax is mexcpp(num1, num2).

The routine defines a class, myData, with member functions display and set_data, and variables v1 and v2. It constructs an object d of class myData and displays the initialized values of v1 and v2. It then sets v1 and v2 to your input, num1 and num2, and displays the new values. Finally, the delete operator cleans up the object.

Handle Files with C++

This example, mexatexit.cpp, illustrates C++ file handling features. To see the C++ code, open the C++ fileopen the C++ file in MATLAB Editor. To compare it with a C code example mexatexit.c, open this fileopen this file in MATLAB Editor.

C Example

The C code example registers the mexAtExit function to perform cleanup tasks (close the data file) when the MEX-file clears. This example prints a message on the screen (using mexPrintf) when performing file operations fopen, fprintf, and fclose.

To build the MEX-file, type:

mex mexatexit.c

Run the example.

x = 'my input string';
Opening file
Writing data to file.

Clear the MEX-file.

clear mexatexit
Closing file

Display the contents of

my input string

C++ Example

The C++ example does not use the mexAtExit function. A fileresource class handles the file open and close functions. The MEX-file calls the destructor for this class (which closes the data file). This example also prints a message on the screen when performing operations on the data file. However, in this case, the only C file operation performed is the write operation, fprintf.

To build the mexatexit.cpp MEX-file, type:

mex mexatexit.cpp


z = 'for the C++ MEX-file';
clear mexatexit
Writing data to file.
Writing data to file.

Display the contents of

my input string
for the C++ MEX-file

Related Examples

Was this topic helpful?