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?

 Respuesta aceptada

James Tursa
James Tursa el 17 de Nov. de 2016

0 votos

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 comentario

Aditya Desai
Aditya Desai el 21 de Nov. de 2016
Thank you for the ideas. It works as expected with index, 0.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Write C Functions Callable from MATLAB (MEX Files) en Centro de ayuda y File Exchange.

Productos

Etiquetas

Preguntada:

el 16 de Nov. de 2016

Comentada:

el 21 de Nov. de 2016

Community Treasure Hunt

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

Start Hunting!

Translated by