User`s manual
Advanced Topics
2-39
creates persistent objects should register a function, using mexAtExit, which
will dispose of the objects. (You can use a
mexAtExit function to dispose of other
resources as well; for example, you can use
mexAtExit to close an open file.)
For example, here is a simple MEX-file that creates a persistent array and
properly disposes of it.
#include "mex.h"
static int initialized = 0;
static mxArray *persistent_array_ptr = NULL;
void cleanup(void) {
mexPrintf("MEX-file is terminating, destroying array\n");
mxDestroyArray(persistent_array_ptr);
}
void mexFunction(int nlhs,
mxArray *plhs[],
int nrhs,
const mxArray *prhs[])
{
if(!initialized) {
mexPrintf("MEX-file initializing, creating array\n");
/* Create persistent array and register its cleanup. */
persistent_array_ptr = mxCreateDoubleMatrix(1, 1, mxREAL);
mexMakeArrayPersistent(persistent_array_ptr);
mexAtExit(cleanup);
initialized = 1;
/* Set the data of the array to some interesting value. */
*mxGetPr(persistent_array_ptr) = 1.0;
} else {
mexPrintf("MEX-file executing; value of first array
element is %g\n",
*mxGetPr(persistent_array_ptr));
}
}