Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

New to MATLAB?

Use of a user defined pointer to mxArray.

Asked by Matt Fig

Matt Fig (view profile)

on 28 Apr 2011

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.



Matt Fig

Matt Fig (view profile)



No products are associated with this question.

1 Answer

Answer by Jan Simon

Jan Simon (view profile)

on 28 Apr 2011
Accepted 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**


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));


James Tursa

James Tursa (view profile)

on 28 Apr 2011

As far as putting variable declarations in the middle of your code, that works in C as well but it is going to depend on how up-to-date your compiler is. It may not be portable.

Matt Fig

Matt Fig (view profile)

on 28 Apr 2011

@ James,
I am using (as I think you know ;)) VC++ 2010 express.

Matt Fig

Matt Fig (view profile)

on 29 Apr 2011

Thanks to all who helped. Both solutions above worked well...

Jan Simon

Jan Simon (view profile)

Contact us