To use a function handle in a mex function with C array as an input to the function handle, you can use mexCallMATLAB( ) with the function handle as an argument to the feval( ) function along with converting the C array to an mxArray inside the C code. E.g., compile this C code (CAUTION: Bare Bones for Example Only ... No Argument Checking Included):
// fnhandle.c , evaluates function handle inside mex function.
// This example assumes function handle takes one input
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
mxArray *rhs[2]; // mxArrays used for input to mexCallMATLAB
double data[3] = {1.0, 2.0, -3.0}; // Some sample data in a C array
double *pr; // Pointer used for copying C array to mxArray
// Copy function handle to input array
rhs[0] = (mxArray *) prhs[0];
// Create input to the function handle
rhs[1] = mxCreateDoubleMatrix(1,3,mxREAL);
// Copy the C array data to the mxArray
pr = (double *) mxGetData(rhs[1]);
pr[0] = data[0]; pr[1] = data[1]; pr[2] = data[2];
// Call feval( ) to evaluate the function handle with one input and put the result in plhs[0]
mexCallMATLAB(1,plhs,2,rhs,"feval");
// Destroy the temporary mxArray
And run it as follows:
Building with 'MinGW64 Compiler (C)'.
MEX completed successfully.
function_handle with value:
function_handle with value:
Note that MATLAB workspace variables used in the function handle are embedded in the function handle at the time of function handle creation, so they get automatically passed into the mex routine as part of the function handle. E.g.,
function_handle with value:
function_handle with value:
In these last examples, the A variable from the MATLAB workspace is embedded in the function handle fh, so it gets passed into the mex routine as part of fh.
If you need to use the results of the function handle call inside the C mex function, then instead of putting the result in plhs[0] you could put the result in a different mxArray and then use a pointer to get at the data of this mxArray. E.g., in the above code you could have done this:
pr = (double *) mxGetData(plhs[0]);
Or using a different output variable the above code could be changed to:
mexCallMATLAB(1,lhs,2,rhs,"feval");
pr = (double *) mxGetData(lhs[0]);
And then dereferenced pr to get at the results of the function handle call inside the C code.