Out-of-Process Execution of C++ MEX Functions
MATLAB® can run C++ MEX functions in a separate process. Running a C++ MEX function in a separate process enables you to:
Isolate the MATLAB process from crashes in the C++ MEX function.
Use some third-party libraries in the C++ MEX function that are not compatible with MATLAB.
Conserve memory by running multiple C++ MEX functions in a single process.
Attach C++ debuggers to the MEX host process.
Interrupt C++ MEX function execution using Ctrl+C
Note
The size of variables passed between C++ and MATLAB is limited to 2 GB when you call a C++ function out-of-process. This limit applies to the data plus supporting information passed between the processes.
How to Run Out of Process
Follow these steps to run your C++ MEX function out of process:
Write your C++ MEX function and build it using the instructions in Build C++ MEX Programs. There are no required code differences between functions written for in-process and out-of-process execution.
Create a MEX host process using the
mexhostfunction.Use the
fevalmethod of thematlab.mex.MexHostobject returned bymexhostto run your C++ MEX function in the host process.
When running out of process, C++ MEX functions always execute in the same folder as the MATLAB current folder. Changing the MATLAB current folder after creating the MEX host object results in the same change in the C++ MEX function context.
Running arrayProduct MEX Function Out of Process
The following example runs the arrayProduct C++ MEX function
out-of-process. The C++ MEX source code is available in the file arrayProduct.cpp. To use this example C++ MEX
function, open the arrayProduct.cpp source file, save it on your
MATLAB path, and build the C++ MEX function using the instructions in Build C++ MEX Programs.
After building the C++ MEX function, start the MEX host process using the
mexhost function. This function returns an object of the
matlab.mex.MexHost class.
Use the feval method to run the arrayProduct
C++ MEX function in the host process. Pass the C++ MEX functions name and arguments
to feval. Return the results to MATLAB by assigning the output of feval.
mh = mexhost;
result = feval(mh,'arrayProduct',2,[1 2 3 4])result =
2 4 6 8 Run arrayProduct in another MEX host process. First create
the MEX host process by calling mexhost again and assigning the
output to a different variable. Then call feval on the new
host.
mh2 = mexhost;
result2 = feval(mh2,'arrayProduct',2,rand(1,10));You can run other C++ MEX functions in the same process using the same
matlab.mex.MexHost object returned by
mexhost.
result2 = feval(mh2,'anotherMexFunction',inputs);Process Lifecycle
The MEX host process lifecycle is coupled to the lifecycle of the
matlab.mex.MexHost object returned by
mexhost. Like any handle object, MATLAB invokes the delete method when the object is no
longer referenced anywhere. If MATLAB invokes delete or if you call delete
on the object explicitly, MATLAB ends the process associated with the MexHost object.
You can end the process explicitly by calling the clear function with any of these
options:
clearthe variable returned by themexhostfunctionclearclasses,clearjava, orclearall
Rebuilding a C++ MEX Function
The mex command automatically
unloads C++ MEX functions before rebuilding them. Therefore, you do not need to
explicitly unload C++ MEX functions from the MEX host process.
You can explicitly unload all C++ MEX functions from a MEX host process by
calling clear
mex or clear
functions. Unload a specific C++ MEX function by calling
clear on the function name.
To prevent the unloading of a C++ MEX function, use the mexLock function. To unlock
the C++ MEX function, use mexUnlock. These functions
set or unset a flag for the C++ MEX function on the host process to control the
unloading of C++ MEX functions.
Getting Information About the MEX Host Process
Use the matlab.mex.MexHost object to get information about the MEX
host process. These properties provide information about the process and loaded
functions.
EnvironmentVariablescontains names and values of environment variables set for the process.Functionscontains the names of all C++ MEX functions loaded into the MEX host process.ProcessNamecontains the name of the MEX host process, which isMATLABMexHostby default.ProcessIdentifiercontains the process identifier.
For more information on these properties, see matlab.mex.MexHost.
Always Run Out of Process
In certain cases, you might always want to run your C++ MEX function out-of-process. For example, running out of process can be necessary if there are third-party library conflicts between MATLAB and the C++ MEX function.
To provide a convenient way to run the C++ MEX function out of process, create a wrapper MATLAB function. The wrapper function creates the MEX host object and runs the C++ MEX function in that process.
For example, suppose that you want to create a wrapper function for the arrayProduct.cpp C++ MEX function that is
included in the documentation as an example. Create a MATLAB function with the name arrayProduct.m and put
this file in a folder that is on the MATLAB path. Build the C++ MEX function and assign a different name for the
compiled MEX file.
The wrapper function creates a matlab.mex.MexHost object that is
assigned to a persistent variable so that the process is not destroyed between
subsequent calls to the wrapper function. The function uses this object to call the
feval
method for out-of-process execution of the C++ MEX function. If the MEX host object
is not valid, then the function creates a MEX host process.
function result = arrayProduct(scalefactor,inputarray) persistent mh if ~(isa(mh,'matlab.mex.MexHost') && isvalid(mh)) mh = mexhost; end result = feval(mh,"arrayProductMEX",scalefactor,inputarray); end
To build the C++ MEX function, open the arrayProduct.cpp source file and save it on your
MATLAB path. Build the C++ MEX function using the instructions in this topic,
Build C++ MEX Programs.
The following command builds MEX file with the root name
arrayProductMEX and puts it in the folder with the wrapper
function, which is assumed to be MyPathFolder in this example.
The mex command creates the folder if
it does not exist.
mex -output arrayProductMEX -outdir MyPathFolder arrayProduct.cpp
To use the C++ MEX function, call it from the command line like any function via the wrapper function.
result = arrayProduct(2,[1 2 3 4]); result
result =
2 4 6 8The following code calls the C++ MEX function in a for loop.
The first call to arrayProduct creates the MEX host process.
Subsequent calls use the same process unless the process is destroyed by, for
example, a crash of the C++ MEX function.
for k = 1:5 results(k,:) = arrayProduct(k,[1 2 3 4]); end results
results =
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
5 10 15 20To destroy the MEX host process, clear all functions that define the MEX host
process variable (mh in this example) as persistent. In this
example, clear the arrayProduct.m function.
clear arrayProduct.mCalling clear
functions causes the destruction of the
matlab.mex.MexHost object that is stored in the persistent
variable and therefore terminates the MEX host process.
Debugging Out-of-Process MEX Functions
You can attach a C++ debugger to your C++ MEX function and set break points to debug your program. Here are the steps to set up and debug a C++ MEX function out of process.
Build C++ MEX source code using the
mexcommand with the-goption to include debugging symbols.Create a host process using the
mexhostfunction. This function returns an object of thematlab.mex.MexHost.Get the process identifier from the
matlab.mex.MexHostobjectProcessIdentifierproperty.Use the process identifier to attach a C++ debugger to the process.
Insert breakpoints in the source code.
Run the C++ MEX function out-of-process using the
fevalmethod.
For information on using specific debuggers, see the documentation for those debuggers.
Debugging Using Microsoft Visual Studio
Ensure Visual Studio® is your selected C++ compiler. This example uses Microsoft® Visual Studio 2015.
cpp = mex.getCompilerConfigurations('C++','Selected'); cpp.Name
ans = 'Microsoft Visual C++ 2015'Build your C++ MEX source code using the
mexcommand with the-goption. This example assumes that you have a C++ MEX source file namedmyMexFunction.cpp.mex -g myMexFunction.cpp
Create a MEX host process and return the
MexHostobject.mh = mexhost;
Start Visual Studio. Do not exit your MATLAB session.
From the Visual Studio Debug menu, select Attach to Process.
In the Attach to Process dialog box, select the
MATLABMexHostprocess, and click Attach.Visual Studio loads data, and then displays an empty code pane.
Open your C++ MEX source file by clicking File > Open > File and selecting the file.
Set a breakpoint by right-clicking the desired line of code and clicking Breakpoint > Insert Breakpoint on the context menu.
In MATLAB, run the C++ MEX function out of process using the
matlab.mex.MexHostfevalmethod.result = feval(mh,'myMexFunction',input1,input2,...)
Use the features provided by the debugger to debug your source code.
Debugging on Linux Systems
On Linux® systems, you can use a debugger such as the GNU®
gdb debugger. Follow these steps to use the
gdb debugger.
Build your C++ MEX source code using the
mexcommand with the-goption. This example assumes that you have a C++ MEX source file namedmyMexFunction.cpp.mex -g myMexFunction.cpp
Create a MEX host process and return the
MexHostobject.mh = mexhost;
Get the process identifier from the
ProcessIdentifierproperty of theMexHostobject. The returned value is a string representing the identifier of the MEX host process. For example,mh.ProcessIdentifier
ans = "13892"The process identifier is different for each process created.
Attach a debugger to the MEX host process from the Linux terminal. For example, using the GNU
gdbdebugger, callgdbwith the C++ MEX file name and the process identifier that you obtained from the MEX host object in MATLAB:gdb myMexFunction -pid=13892
Set break points in the C++ MEX function. For example, using
gdb, set the break point inmyMexFunction.cppat line 21:break myMexFunction.cpp:21
From MATLAB, run the C++ MEX function out-of-process using the
matlab.mex.MexHostfevalmethod.result = feval(mh,'myMexFunction',input1,input2,...)
MATLAB waits for a response from the debugger.
From the Linux terminal, use the features provided by the debugger to debug your source code.
Debugging on Macintosh Systems
On Macintosh systems, use the LLDB debugger.
Build your C++ MEX source code using the
mexcommand with the-goption. This example assumes that you have a C++ MEX source file namedmyMexFunction.cpp.mex -g myMexFunction.cpp
Create a MEX host process and return the
MexHostobject.mh = mexhost;
Get the process identifier from the
ProcessIdentifierproperty of theMexHostobject. The returned value is a string representing the identifier of the MEX host process.mh.ProcessIdentifier
ans = "13892"The process identifier is different for each process created.
Attach a debugger to the MEX host process from the macOS Terminal. Call
lldbwith the MEX host process identifier that you obtained from the MEX host object in MATLAB. For example, assuming the process identifier is13892, attach the LLDB debugger to this process:lldb -p 13892
Set a break points in your source code. For example, this command sets a break point in
myMexFunction.cppat line number 21.breakpoint set -f myMexFunction.cpp -l 21
From MATLAB, run the C++ MEX function out-of-process using the
matlab.mex.MexHostfevalmethod.result = feval(mh'myMexFunction',input1,input2,...)
MATLAB waits for a response from the debugger.
Enter
Corcontinuefrom the macOS Terminal. Program execution stops at breakpoints.From the macOS Terminal, use the features provided by the debugger to debug your source code.