Wrong read in mex function

Hi, in main.m i create numeri (vector of int).
In mex file i have:
int *numeri;
void mexFunction(int nlhs , mxArray *plhs[] , int nrhs , const mxArray *prhs[]) {
// Parse "numeri"
if ( mxGetNumberOfDimensions( prhs[2] ) != 2 || mxGetN(prhs[2]) != 1 )
mexErrMsgIdAndTxt("InvalidInput:numeri","'numeri' must be a column vector");
numeri = (int*) mxGetData(prhs[2]);
for(int i=0;i<10;i++)
printf("%d \n",numeri[i]);
}
the printed values are not the same that I get in the main. Why?
Thanks,
Davide

Antworten (1)

Geoff Hayes
Geoff Hayes am 13 Aug. 2014

0 Stimmen

Davide - how are you calling this function? And in particular, what are the inputs? I suspect that there might be a problem with the third input to this function.
I took your code and placed it in a function called testfunc.c and then ran mex testfunc.c. In the Command Window, I typed the following two lines
v = [1:10]';
testfunc(2,3,v)
and the output from the printfs in the C code was
0
1072693248
0
1073741824
0
1074266112
0
1074790400
0
1075052544
So not the 1,2,3,...,10. This "error" actually makes sense. In the Command Window, check the data type of the vector v
class(v)
ans =
double
So we are passing in an array of doubles, but the C-code is expecting an array of integers
int *numeri;
and later
numeri = (int*) mxGetData(prhs[2]);
So we have to change the data type of the input data from double to int32. We can do this as
v = int32([1:10]');
testfunc(2,3,v)
and the output this time is
1
2
3
4
5
6
7
8
9
10
Hope that this helps!

Kategorien

Mehr zu Write C Functions Callable from MATLAB (MEX Files) finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 13 Aug. 2014

Beantwortet:

am 13 Aug. 2014

Community Treasure Hunt

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

Start Hunting!

Translated by