Array of int at the output of a mex file
Mostrar comentarios más antiguos
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.
Respuesta aceptada
Más respuestas (2)
Jan
el 15 de Mzo. de 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
el 15 de Mzo. de 2012
3 comentarios
Friedrich
el 15 de Mzo. de 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
el 15 de Mzo. de 2012
And IMPORTANT:
delte this line
partitions = (int *)malloc(sizeof(int)*round(log2(N))*2+1);
You already allocated the memory for partitions!
Carine
el 15 de Mzo. de 2012
Categorías
Más información sobre Write C Functions Callable from MATLAB (MEX Files) en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!