Clear Filters
Clear Filters

Struct as input to mex file

8 views (last 30 days)
Aditya Desai
Aditya Desai on 16 Nov 2016
Commented: Aditya Desai on 21 Nov 2016
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?

Accepted Answer

James Tursa
James Tursa on 17 Nov 2016
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.
  1 Comment
Aditya Desai
Aditya Desai on 21 Nov 2016
Thank you for the ideas. It works as expected with index, 0.

Sign in to comment.

More Answers (0)

Categories

Find more on MATLAB Compiler in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!