Wrong read in mex function
2 views (last 30 days)
Show older comments
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
0 Comments
Answers (1)
Geoff Hayes
on 13 Aug 2014
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!
0 Comments
See Also
Categories
Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!