Use of a user defined pointer to mxArray.

6 views (last 30 days)
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.

Accepted Answer

Jan
Jan on 28 Apr 2011

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));
  8 Comments
Matt Fig
Matt Fig on 28 Apr 2011
@ James,
I am using (as I think you know ;)) VC++ 2010 express.
Thanks.
Matt Fig
Matt Fig on 29 Apr 2011
Thanks to all who helped. Both solutions above worked well...

Sign in to comment.

More Answers (0)

Categories

Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!