How can I make memory persistent between calls to a MEX-file in MATLAB?
Show older comments
I would like to know if memory allocated with mxCalloc remains persistent between calls to a MEX-file.
Accepted Answer
More Answers (1)
James Tursa
on 2 Jan 2024
So, the accepted answer has bugs. Namely:
- They don't include the header for memcpy
- They don't check the input argument properly
Either of these can lead to a MATLAB crash if the input isn't as expected. Corrected and more robust code that doesn't rely on the messy memcpy and can correctly handle unexpected or missing input argument is:
// test.c
#include "mex.h"
static double *myarray = NULL;
void exitFcn() {
if (myarray != NULL)
mexPrintf("Free'ing the persistent memory\n");
mxFree(myarray);
}
void mexFunction(int nlhs,mxArray *plhs[],int nrhs, const mxArray *prhs[])
{
if (myarray==NULL) {
/* since myarray is initialized to NULL, we know
this is the first call of the MEX-function
after it was loaded. Therefore, we should
set up myarray and the exit function. */
/* Allocate array. Use mexMakeMemoryPersistent to make the allocated memory persistent in subsequent calls*/
mexPrintf("First call to MEX-file\n");
myarray = mxCalloc(1,8);
mexMakeMemoryPersistent(myarray);
mexAtExit(exitFcn);
}
mexPrintf("Old value was '%f'.\n",myarray[0]);
if( nrhs ) {
if (!mxIsNumeric(prhs[0]) || mxGetNumberOfElements(prhs[0]) == 0)
mexErrMsgTxt("Input must be non-empty numeric");
myarray[0] = mxGetScalar(prhs[0]);
mexPrintf("New value is '%f'.\n",myarray[0]);
}
}
Categories
Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!