MATLAB input structure with unsigned char to MEX file
I tried to inject this structure from MATLAB into my MEX: file struct('speed',{100.3},'nr',{55.4},'on',{54})
, but the last value that is defined in my MEX file as unsigned char
read as zero before calling my C function? The two double values ββwork as intended.
struct post_TAG
{
double speed;
double nr;
unsigned char on;
};
const char *keys[] = { "speed", "nr", "on" };
void testmex(post_TAG *post)
{
...
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, mxArray *prhs[])
{
post_TAG post;
int numFields, i;
const char *fnames[3];
mxArray *tmp;
double *a,*b;
unsigned char *c;
numFields=mxGetNumberOfFields(prhs[0]);
for(i=0;i<numFields;i++)
fnames[i] = mxGetFieldNameByNumber(prhs[0],i);
tmp = mxGetField(prhs[0],0,fnames[0]);
a=(double*)mxGetData(tmp);
tmp = mxGetField(prhs[0],0,fnames[1]);
b=(double*)mxGetData(tmp);
tmp = mxGetField(prhs[0],0,fnames[2]);
c=(unsigned char*)mxGetData(tmp);
mexPrintf("POST0, speed=%f, nr=%f, on=%u\n",*a,*b,*c);
post.speed = *a;
post.nr = *b;
post.on = *c;
testmex(&post);
}
source to share
In struct
, defined as struct('speed',{100.3},'nr',{55.4},'on',{54})
, the field on
is double
. Pass like uint8
from MATLAB:
struct('speed',{100.3},'nr',{55.4},...
'on',{uint8(54)}),
Any numeric value without a specified type in MATLAB is double
.
Also note that for reading a scalar value, the problem is somewhat simplified by mxGetScalar
. It will return one value double
for any underlying data type.
unsigned char s = (unsigned char) mxGetScalar(...); // cast a double to unsigned char
source to share