首页 文章

MATLAB输入struct with unsigned char into MEX file

提问于
浏览
3

我试图将这个结构从MATLAB输入到我的MEX文件中: struct('speed',{100.3},'nr',{55.4},'on',{54}) ,但是我的MEX文件中定义的最后一个值 unsigned char 在调用我的C函数之前读出为零?两个double值的工作方式与预期的一样 .

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);  
}

1 回答

  • 2

    在定义为 struct('speed',{100.3},'nr',{55.4},'on',{54})struct 中,字段 ondouble . 从MATLAB传递为 uint8

    struct('speed',{100.3},'nr',{55.4},...
        'on',{uint8(54)}),
    

    在MATLAB中没有指定类型的任何数值都是 double .

    另请注意,对于读取标量值, mxGetScalar 会稍微简化问题 . 它将为任何基础数据类型返回一个 double 值 .

    unsigned char s = (unsigned char) mxGetScalar(...); // cast a double to unsigned char
    

相关问题