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';
mexatexit(x)
Opening file matlab.data.
Writing data to file.

Clear the MEX-file.

clear mexatexit
Closing file matlab.data.

Display the contents of matlab.data.

type matlab.data
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

Type:

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

Display the contents of matlab.data.

type matlab.data
my input string
for the C++ MEX-file

Related Examples

Was this topic helpful?