Using mxGetPr vs mxGetData

佐手、 提交于 2019-12-01 23:40:40

mxGetData returns a void pointer which must be cast to a pointer of the correct datatype.

In C, mxGetData returns a void pointer (void *). Since void pointers point to a value that has no type, cast the return value to the pointer type that matches the type specified by pm

In your case, I'm assuming that although it looks like you've passed in an integer, it's actually a double since that is MATLAB's default datatype so your issue is due to the fact that you try to convert it to an unsigned short pointer.

myMEX_1(1)          % Passes a double
myMEX_1(uint16(1))  % Passes an integer

To fix this, we would need to cast the output of mxGetData as a double pointer instead, and then dereference it, cast it and assign it

frameCount = (unsigned short)*(double*)mxGetData(prhs[0]);

mxGetPr is the same as mxGetData except that it automatically casts the output of mxGetData as a double pointer. Thus, it saves you a step but is only appropriate for double inputs (which you have).

If you want to handle inputs of multiple types appropriately, you'll need to check the type of the input using either mxIsDouble or mxIsClass.

if ( mxIsDouble(prhs[0]) ) {
    frameCount = (unsigned short)*mxGetPr(prhs[0]);
} else if ( mxIsClass(prhs[0], "uint16") {
    frameCount = *(unsigned short*)mxGetData(prhs[0]);
} else {
    mexPrintf("Unknown datatype provided!");
    return;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!