Passing int to mex file

조회 수: 12 (최근 30일)
Fran
Fran 2014년 8월 5일
댓글: Jed 2020년 1월 28일
Hello,
I wrote a MEX routine that calls a C function which uses "int" rather than double.
The way I fetch the array from MatLab is through a command like:
nc = (int *) mxGetPr(prhs[1]);
However, this works only if, when calling the function from MatLab, I do:
function(...,int32(nc),...);
Otherwise, it crashes, as it calculates an index incorrectly, which I then use to access some elements of an array.
I tried passing the array as a double, and then casting it to a new array within the mex file. Like this:
nc_double = (double *) mxGetPr(prhs[1]);
nc *int;
for (int i=0; i<size_nc; n++)
{
nc[i] = (int) nc_double[i];
}
It compiled, but have me an error: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) using the debugger.
I wonder if there is a more robust way of doing this? Someone on the Matlab side might forget to convert the culprits to int32 and crash the program.
Cheers,
Francesco
  댓글 수: 1
Adam
Adam 2014년 8월 5일
In terms of someone on the Matlab side forgetting to convert the data you could just write a .m wrapper function for the mex which does the conversion and anyone using the code uses that rather than calling the mex directly. That is what myself and colleagues tend to do.

댓글을 달려면 로그인하십시오.

채택된 답변

Friedrich
Friedrich 2014년 8월 5일
편집: Friedrich 2014년 8월 5일
Hi,
have you tried
int a = (int)*mxGetPr(prhs[0]);
This will work for double values only. In order to make this work for all kinf of data you would need to get the classID of the input argument using mxGetClassID and cast accordingly.
Or if you are lazy call back to MATLAB and let it do the cast:
mxArray *lhs[1];
int a;
mexCallMATLAB(1,lhs,1,&(prhs[0]),"int32");
a = *(int*)mxGetData(lhs[0]);
mexPrintf("%d\n",a);
  댓글 수: 3
Friedrich
Friedrich 2014년 8월 5일
Right, that would be a scalar only. This wont work for an array. However the mexCallMATLAB approach will work for arrays. Simply use
mxArray *lhs[1];
int* a;
mexCallMATLAB(1,lhs,1,&(prhs[0]),"int32");
a = (int*)mxGetData(lhs[0]);
Jed
Jed 2020년 1월 28일
If you just had a scalar and you didn't know that it was a double, you could also use this:
int a = (int)mxGetScalar(prhs[0]);

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 MATLAB Compiler에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by