How to read an integer array in a MEX function

I am passing an integer array of type uint8 from MATLAB to a MEX function. How to read these values? I tried using:

int *n; n = (int * ) mxGetData(prhs[0]); 

but the values ​​come out like garbage. I also tried

 double *n; n= mxGetPr(prhs[0]); 

in this case, spam values ​​also appear.

What is the solution to this?

Basically I want to read an integer value in a MEX function, but mxGetPr returns a double type.

+8
matlab mex
source share
2 answers

Take a look at the demo expl.c MEX function you can open in MATLAB using

 edit([matlabroot '/extern/examples/mex/explore.c']); 

There you will find a bunch of functions whose names begin with analyze_ , and then of type (for example, analyze_uint8 ). In these functions, you will see the output of mxGetData calls that will be passed to a specific type C, for example:

 pr = (unsigned char *)mxGetData(array_ptr); 

pr now points to the real part of array_ptr , an unsigned char array.

+8
source share

You have to make sure that the number of bytes read and the interpretation of these bytes are the same in the input (which come from Matlab) and in the output array (the array that you read in the mex function). Since uint8 is 8 bits long, both double and int will read the wrong number of bytes and interpret these bytes incorrectly.

Try including the stdint.h header and use the uint8_t data uint8_t for the array to read.

+1
source share

All Articles