MATLAB: Can the MEX-file in MATLAB 7.3 (R2006b) not reliably access mxArrays after the main mexFunction() exits

MATLAB

I would like to access mxArrays after my mexFunction() call finishes, either from a child process or in a subsequent MEX-function call. I obtain these mxArrays using either the mxCreate*Array() functions or mexGetVariable().

Best Answer

These mxArrays can be removed from MATLAB's tracking by passing them to mexMakeArrayPersistent(). However, the caller of mexMakeArrayPersistent() implicitly takes ownership of that array and must ensure that at some point it is freed (via mxDestroyArray()) or else this will produce a memory leak.
The attached example MEX-files demonstrate a failure (memtest1.cpp) as well the correct management of the persistent mxArray (memtest2). To execute these, initialize the variable "x" and call each MEX-function twice, as demonstrated below.
memtest1 will cause a segmentation violation:
mex -v memtest1.cpp
x = 7;
memtest1
memtest1
Initializing pointer
Ptr: 287730336
Value of x(1): 7.000000
Existing pointer
Ptr: 287730336
Probably going to segv:
------------------------------------------------------------------------
Segmentation violation detected at Mon Oct 02 19:45:57 2006
------------------------------------------------------------------------
memtest2 will execute successfully:
mex -v memtest2.cpp
x = 7;
memtest2
memtest2
Existing pointer
Ptr: 324198688
Value of x(1): 7.000000
Existing pointer
Ptr: 324198688
Value of x(1): 7.000000
This type of interface will allow you to control the managment of certain mxArrays. However, they must be correctly managed using mxDestroyArray() in your program, as they are no longer tracked by the MATLAB memory manager.