MEX question: How to set scalar and array values within plhs[0] struct?
Show older comments
I've been pulling my hair out about this one for a while. I have a C struct shown below, and am trying to convert it to be the exact same type of setup to be returned within plhs[0]. However when I print the contents of the first value of the plhs struct, I get -nan. I'd really apreciate the help to figure out why this isn't working correctly.
Here's the C struct:
typedef struct {
boolean_T nL;
int lID;
int mID;
int mT;
int tID;
int tT;
double t0;
double PIP[3];
double UFD[3];
} struct1_T;
Here's my C code to set the "nL" boolean within plhs[0]:
int dims[2];
dims[0] = 1;
dims[1] = 1;
mwIndex m = 0;
const char *names[] = {"nL","lID","mID","mT","tID","tT","t0","PIP","UFD"};
plhs[0] = mxCreateStructArray(2, dims, 9, names);
int conv = data[0].nL; //data is a struct1_T struct shown above
double temp = conv;
mexPrintf("val: %f\n", temp);
mxSetField(plhs[0], 0, names[0], mxCreateDoubleScalar(temp));
double *print = mxGetField(plhs[0],m,"nL");
mexPrintf("Output_0: %f\n" print[0]);
And here is the output I get when I run it:
val: 0.000000
Output_0: -nan
Answers (1)
James Tursa
on 7 Aug 2018
Edited: James Tursa
on 7 Aug 2018
mxGetField returns a pointer to mxArray, not pointer to double. You need to get at the data with the appropriate function. E.g.,
double *print = mxGetPr(mxGetField(plhs[0],m,"nL")); // R2017b memory model
or
double *print = mxGetDoubles(mxGetField(plhs[0],m,"nL")); // R2018a memory model
The above is quick and dirty code. Normally one would check the result of mxGetField first to make sure it is not NULL and that it contains a non-empty double variable before calling mxGetPr or mxGetDoubles.
Didn't the compiler give you a warning about your current code converting a (mxArray *) type to a (double *) type? In C++ that line would have generated a compile error.
2 Comments
Jerry Painter
on 7 Aug 2018
Edited: Jerry Painter
on 7 Aug 2018
James Tursa
on 7 Aug 2018
Edited: James Tursa
on 7 Aug 2018
You are using a struct index of 6 now instead of 0. What are the values of dims[0] and dims[1]? Are you writing/reading beyond the end of the array?
Also, you are printing the result of the mxGetPr() call using a floating point format. That's not going to work. You need to dereference that pointer. E.g.,
mexPrintf("plhs[0]_t0: %f\n",*mxGetPr(mxGetField(plhs[0],6,"t0")));
Categories
Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!