MATLAB: Use of a user defined pointer to mxArray.

mex

This has always bugged me about working with MEX-functions. Here is how I always end up working with the return argument from a MEX- function.
plhs[0] = mxCreateNumericArray(I,J,mxDOUBLE_CLASS,mxREAL);
for (ii=0;ii<M;ii++)
mxGetPr(plhs[0])[ii] = mxGetPr(prhs[0])[ii];
This works fine, but what I would like to do is find a way to not have to call mxGetPr every time through each and every loop in the file. To this end I tried this (starting with lhs):
mxArray *Ar; // initialize at beginning of file.
plhs[0] = mxCreateNumericArray(I,J,mxDOUBLE_CLASS,mxREAL); // SWITCH
Ar = mxGetPr(plhs[0]);// What is the point of this if I can't use it?
for (ii=0;ii<M;ii++)
*(Ar+ii) = mxGetPr(prhs[0])[ii];
But I get compile errors referencing: 'mxArray *' : unknown size.
The problem is that the return type is not known at compile time, so is there no way around using mxGetPr in such a case? I have had similar errors when working only with the prhs.
Thanks.

Best Answer

The value replied by mxGetPr is a pointer to the data of the mxArray and therefore a (double *). (mxArray *) is a pointer to a struct. In consequence this does not work:

mxArray *Ar;             % **wrong**
Ar = mxGetPr(plhs[0]);   % **wrong**

Correct:

double *Ar;
Ar = mxGetPr(plhs[0]);

Or equivalent:

Ar = (double *) mxGetData(plhs[0]);

Modern compilers use the fast SSE unit to copy memory blocks in chunks of 128 or 256 bits, if you call MEMCPY. Therefore I suggest this:

plhs[0] = mxCreateNumericArray(I,J,mxDOUBLE_CLASS,mxREAL);
memcpy(mxGetPr(plhs[0]), mxGetPr(prhs[0]), M * sizeof(double));