【问题标题】:MATLAB input struct with unsigned char into MEX fileMATLAB 将带有 unsigned char 的结构输入到 MEX 文件中
【发布时间】:2015-07-03 11:06:44
【问题描述】:

我尝试将此结构从 MATLAB 输入到我的 MEX 文件中:struct('speed',{100.3},'nr',{55.4},'on',{54}),但在我的 MEX 文件中定义为 unsigned char 的最后一个值在调用我的 C 函数之前读出为零?这两个双精度值按预期工作。

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

【问题讨论】:

    标签: matlab mex


    【解决方案1】:

    在定义为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
    

    【讨论】:

    • 另请注意,您应该使用mxGetPr 而不是(double*)mxGetData。 IMO 少一个演员是一件好事。
    • @Henrik 没问题。有帮助吗?如果是这样,请接受(绿色检查),并按您的意愿投票。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多