Array of int at the output of a mex file
Ältere Kommentare anzeigen
I am trying to create a mex function whose entry is an integer and whose output is an array of integers. So the function looks like: int *myFunction(unsigned int N). In the mexFunction, I declare a variable *vari of type int and then
N = mxGetScalar(prhs[0]);
/* assign a pointer to the output */
siz= 2*round(log2(N))+1;
plhs[0] = mxCreateDoubleMatrix(1,siz, mxREAL);
vari = (int*) mxGetPr(plhs[0]); */
/* Call the subroutine. */
vari = myFunction(N);
mexPrintf("The first value is %d\n", vari[0]);
The thing is the first value is the correct one (and the other ones were checked and were correct as well) but when I call the routine mxFunction(16), I get only 0's as output. I guess it is because my output is an array of int but I don't know how to solve the problem. Any hint? Cheers.
Akzeptierte Antwort
Weitere Antworten (2)
Jan
am 15 Mär. 2012
You define "partitions" twice:
- partitions = (int*) mxGetPr(plhs[0]); This is dangerous, because myGetPr replies a pointer to a double array. Better use mxGetData as in the commented section.
- partitions = gft_1dPartitions(N); This overwrites the former definition.It is recommended to use mxMalloc instead of malloc inside MEX functions. If you really want to use malloc, do not forget to let "free" release the reserved memory afterwards.
I think, you want to forward the pointer to the reserved memory block to the subfunction:
taille = 2*round(log2(N))+1;
plhs[0] = mxCreateNumericMatrix(1, taille, mxINT32_CLASS, mxREAL);
partitions = (int*) mxGetData(plhs[0]);
gft_1dPartitions(N, partitions);
Then you write directly to the memory in the lefthand side of the Mex function and the malloc inside the subfunction is removed.
Carine
am 15 Mär. 2012
3 Kommentare
Friedrich
am 15 Mär. 2012
You could change your code according to mine and it should work. So instead
int *gft_1dPartitions(unsigned int N)
do
void gft_1dPartitions(unsigned int N, int* partitions)
And call it not like this
partitions = gft_1dPartitions(N);
Do it like this
gft_1dPartitions(N,partitions);
Friedrich
am 15 Mär. 2012
And IMPORTANT:
delte this line
partitions = (int *)malloc(sizeof(int)*round(log2(N))*2+1);
You already allocated the memory for partitions!
Carine
am 15 Mär. 2012
Kategorien
Mehr zu Write C Functions Callable from MATLAB (MEX Files) finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!