Struct as input to mex file

9 次查看(过去 30 天)
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?

采纳的回答

James Tursa
James Tursa 2016-11-17
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 个评论
Aditya Desai
Aditya Desai 2016-11-21
Thank you for the ideas. It works as expected with index, 0.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 MATLAB Compiler 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by