フィルターのクリア

mexAtExit and static variables

7 ビュー (過去 30 日間)
Jason
Jason 2011 年 11 月 10 日
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 Center および File ExchangeWrite 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