You are correct that the plhs = mxCreateNumericMatrix(...)
is not needed. Also, note that nlhs
is the number of left-hand-sides you supply in MATLAB - so in your case, you're calling it with 2 left-hand-sides. Here's how to return trivial scalar values:
plhs[0] = mxCreateDoubleScalar(2);
plhs[1] = mxCreateDoubleScalar(3);
To handle your actual return values, you'll need to do something to copy the values out of foo
and into a newly-created mxArray. For example, if your function returned doubles, you might do this:
double * values;
int numValues;
myFcn(&values, &numValues);
/* Build a 1 x numValues real double matrix for return to MATLAB */
plhs[0] = mxCreateDoubleMatrix(1, numValues, mxREAL);
/* Copy from 'values' into the data part of plhs[0] */
memcpy(mxGetPr(plhs[0]), values, numValues * sizeof(double));
EDIT Of course someone somewhere needs to de-allocate values
in both my example and yours.
EDIT 2 Complete executable example code:
#include <string.h>
#include "mex.h"
void doStuff(double ** data, int * numData) {
*numData = 7;
*data = (double *) malloc(*numData * sizeof(data));
for (int idx = 0; idx < *numData; ++idx) {
(*data)[idx] = idx;
}
}
void mexFunction( int nlhs, mxArray * plhs[],
int nrhs, const mxArray * prhs[] ) {
double * data;
int numData;
doStuff(&data, &numData);
plhs[0] = mxCreateDoubleMatrix(1, numData, mxREAL);
memcpy(mxGetPr(plhs[0]), data, numData * sizeof(double));
free(data);
plhs[1] = mxCreateDoubleScalar(numData);
}