MATLAB: Struct as input to mex file

MATLABmexstruct

I want to provide a struct as an input to mex function in C and then use the data stored as in a particular field in the computational routine. The C code is as follows:
#include "mex.h"
#include <math.h>
#include <string.h>
double times_two(double W0[]){
double A;
return A = 2*W0[0];
}
void mexFunction(int nlhs, mxArray * plhs[], int nrhs,
const mxArray * prhs[]) {
double A, *W0;
double *tmp;
mwIndex idx = 1;
int ifield, nfields;
const char **fname; /* pointers to field names */
nfields = mxGetNumberOfFields(prhs[0]);
fname = mxCalloc(nfields, sizeof(*fname));
for (ifield=0; ifield< nfields; ifield++){
fname[ifield] = mxGetFieldNameByNumber(prhs[0],ifield);
if (strcmp(fname[ifield],"W0") == 0){
tmp = mxGetPr(mxGetFieldByNumber(prhs[0],idx,ifield));
W0 = tmp;
}
}
A = times_two(W0);
mexPrintf("A = %%f",A);
}
The matlab code for calling this would be something like:
a.W0 = 1.5;
a.somethingElse = 2;
test_struct(a); % Mex function
The mex function compiles successfully. However, at runtime, I get a segmentation fault at W0 = tmp; What am I doing wrong here?

Best Answer

You are passing in a 1x1 struct, so the only valid index inside a mex routine is 0 since the indexing is 0-based. So change this line:
mwIndex idx = 1;
to this:
mwIndex idx = 0;
And to make your program more robust to unexpected inputs, I would advise putting in many other checks. E.g., check to see that the number of inputs and outputs is as required, that the input variable is in fact a struct, that the number of elements of this struct is as expected, that the field element extracted is not NULL, that the field element is a non-empty double, etc etc.