mexAtExit and static variables

4 次查看(过去 30 天)
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?

采纳的回答

Kaustubha Govind
Kaustubha Govind 2011-11-10
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 个评论
Jason
Jason 2011-11-10
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 2011-11-10
You just need to use mxGetPr to get the internal double* representation to pass it to native libraries.

请先登录,再进行评论。

更多回答(1 个)

Walter Roberson
Walter Roberson 2011-11-10
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 个评论
Jason
Jason 2011-11-10
dcopy is in BLAS and copies one vector to another.
stride = 1 is correct I think.
%lf does not change the behavior.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Write C Functions Callable from MATLAB (MEX Files) 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by