mexAtExit and static variables

4 views (last 30 days)
Jason
Jason on 10 Nov 2011
I have a quick question regarding static variables in mex files. Basically it is not behaving as I expected. However I'm not a programmer so perhaps this is simply a silly error. I have the problem in a large mex file but the following snippit is enough to demonstrate the issue.
---------------------
#include stuff
static double *X = NULL;
static void clearX(void)
{
mexPrintf("Clearing X\n");
mxFree(X);
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
double *X2;
ptrdiff_t stride = 1, m;
m = (ptrdiff_t)mxGetM(prhs[0]);
if( X == NULL ){
mexPrintf("\tAllocating Memory for X.\n");
X = (double *) mxMalloc((size_t) m*sizeof(double));
mexAtExit(clearX);
}
X2 = mxGetPr(prhs[0]);
mexPrintf("\tCopying %f to X.\n",X2[0]);
mexPrintf("\tX was %f.\n",X[0]);
dcopy(&m,X2,&stride,X,&stride);
mexPrintf("\tX is now %f.\n",X[0]);
}
--------------------------------------
This is then compiled
mex -g -O -largeArrayDims testMex.c -lmwblas
I then test it:
>> a=randn(1);testMex(a)
Allocating Memory for X.
Copying -0.271685 to X.
X was 0.000000.
X is now -0.271685.
>> a=randn(1);testMex(a)
Copying 0.604548 to X.
X was 0.000000.
X is now 0.604548.
So the question is, if X is not being freed (clearX is not being called) and its not being reallocated, why is X reset to 0.0?

Accepted Answer

Kaustubha Govind
Kaustubha Govind on 10 Nov 2011
You should consider declaring your persistent variable X as an mxArray, since you are using MATLAB-managed memory anyway. mxArrays can then be declared as persistent using mexMakeArrayPersistent, which ensures that MATLAB doesn't release that memory (I don't know if you can do that with built-in pointers allocated using mxMalloc). Please see Persistent Arrays for more information.
  2 Comments
Jason
Jason on 10 Nov 2011
I need to use BLAS and LAPACK on the arrays. Using an mxArray seems to add more complexity as one needs the mxArray and a separate double pointer for each static variable, but I just swiched it over and it seems to work as expected.
Thank you
Kaustubha Govind
Kaustubha Govind on 10 Nov 2011
You just need to use mxGetPr to get the internal double* representation to pass it to native libraries.

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 10 Nov 2011
You are printing out double precision numbers in the C code. You should be using %lf rather than %f .
Using a stride of 1 is something I would cross-check, but I am having difficulty finding a reference for what dcopy() does.
  1 Comment
Jason
Jason on 10 Nov 2011
dcopy is in BLAS and copies one vector to another.
stride = 1 is correct I think.
%lf does not change the behavior.

Sign in to comment.

Categories

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

Community Treasure Hunt

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

Start Hunting!