Start MATLAB Sessions from C++
You can start MATLAB® engine sessions from C++ using the MATLAB Engine API for C++.
These examples show how to start a MATLAB engine session from your C++ program synchronously or asynchronously and
in-process or out-of-process. To start the session, use one of these utility functions,
which are defined in the matlab::engine namespace:
matlab::engine::startMATLAB— Start a MATLAB session synchronously.matlab::engine::startMATLABAsync— Start a MATLAB session asynchronously.
For setup and build instructions, see Requirements to Build C++ Engine Applications.
Start MATLAB Session Synchronously
Start MATLAB from C++ synchronously and out-of-process. startMATLAB returns a unique pointer
to the MATLABEngine instance.
#include "MatlabEngine.hpp"
void startMLSession() {
using namespace matlab::engine;
// Start MATLAB engine synchronously
std::unique_ptr<MATLABEngine> matlabPtr = startMATLAB();
}Start MATLAB Session In-Process
By default, MATLAB runs out-of-process. You can run MATLAB in the same process as your
C++ application by calling either matlab::engine::startMATLAB or
matlab::engine::startMATLABAsync with mode
set to MATLABApplicationMode::IN_PROCESS. To explicitly call
MATLAB out-of-process, set mode to
MATLABApplicationMode::OUT_OF_PROCESS. For more information
about mode, see matlab::engine::startMATLAB
Parameters. (since R2026a)
For example, start MATLAB from C++ in-process.
#include "MatlabEngine.hpp"
void startMLSession() {
using namespace matlab::engine;
// Start MATLAB engine in-process
std::unique_ptr<MATLABEngine> matlabPtr = startMATLAB(MATLABApplicationMode::IN_PROCESS);
}Start MATLAB Session Asynchronously
Start MATLAB from C++ asynchronously and out-of-process. Use
FutureResult::get to retrieve the unique pointer to the
MATLABEngine instance returned by
startMATLABAsync.
#include "MatlabEngine.hpp"
void startMLSessionAsync() {
using namespace matlab::engine;
// Start MATLAB engine asynchronously out-of-process
FutureResult<std::unique_ptr<MATLABEngine>> matlabFuture = startMATLABAsync();
std::unique_ptr<MATLABEngine> matlabPtr = matlabFuture.get();
}Start MATLAB with Startup Options
You can start a MATLAB session using supported MATLAB startup options. For general startup options, see Commonly Used Startup Options. For options supported by the engine, see
matlab::engine::MATLABEngine.
This example starts MATLAB using the -r startup option and the
matlab.engine.ShareEngine option. Create a vector with each
option as an element.
#include "MatlabEngine.hpp"
void startMLOptions() {
using namespace matlab::engine;
// Create an option vector with the
// startup option -r and the
// matlab.engine.ShareEngine option
std::vector<String> optionVec;
optionVec.push_back(u"-r");
optionVec.push_back(u"matlab.engine.shareEngine");
// Start MATLAB out-of-process
std::unique_ptr<MATLABEngine> matlabPtr = startMATLAB(optionVec);
}See Also
matlab::engine::startMATLAB | matlab::engine::startMATLABAsync