Create host process for C++ MEX function
Run C++ MEX Function Out of Process
Create a host process and run a C++ MEX function in that process.
arrayProduct.cpp C++ MEX file contains
the source code for a function that multiplies an array by a scalar input
and returns the resulting array. Open this file and save it on your
MATLAB® path. Build the C++ MEX source file using the
mex command. To set up the
MEX build, follow the instructions in Build C++ MEX Programs.
Create a host process. The
mexhost function returns a
mh = mexhost;
feval method of the
matlab.mex.MexHost object to evaluate the C++ MEX function in
the host process.
result = feval(mh,"arrayProduct",10,[2,4,6,8])
result = 20 40 60 80
Find Process ID
You can use the
MexHost object to find the
identifier of the process created by the
mh = mexhost; mh.ProcessIdentifier
ans = "13336"
Each call to
mexhost creates a process.
Set Environment Variable for Library
Set the value of environment variable
envVal1 and the value of
s = ["envName1","envVal1" "envName2","envVal2"]; mh = mexhost("EnvironmentVariables",s)
mh = MexHost with properties: ProcessName: "MATLABMexHost" ProcessIdentifier: "19344" Functions: [0×0 string] EnvironmentVariables: "envName1" "envVal1" "envName2" "envVal2"
envVariables — Environment variables and values
n-by-2 string array
Environment variables and values, specified as an n-by-2 string array. Non-ASCII characters are not supported. The first column is the name of the environment variable and the second column is the value.
mh — Host process
Host process, returned as a
Use this process to run a C++ MEX function outside of the MATLAB process.
Process Life Cycle
MATLAB terminates the process when the object returned by
mexhost is destroyed. MATLAB destroys the object when any of the following occur.
The MEX host variable returned by
mexhostgoes out of scope, causing MATLAB to destroy the object.
deletemethod is called on the MEX host variable explicitly.
clearfunction is called on the MEX host variable and there are no other references to the object.
clearfunction is called with any of these options:
clear classes, or
Unload C++ MEX Functions
Introduced in R2019a