mexAtExit (C and Fortran)

Register function to call when MEX function clears or MATLAB terminates

C Syntax

#include "mex.h"
int mexAtExit(void (*ExitFcn)(void));

Fortran Syntax

#include "fintrf.h"
integer*4 mexAtExit(ExitFcn)
subroutine ExitFcn()



Pointer to function you want to run on exit


Always returns 0.


Use mexAtExit to register a function to call just before clearing the MEX function or terminating MATLAB®. mexAtExit gives your MEX function a chance to perform tasks such as freeing persistent memory and closing files. Other typical tasks include closing streams or sockets.

Each MEX function can register only one active exit function at a time. If you call mexAtExit more than once, MATLAB uses the ExitFcn from the more recent mexAtExit call as the exit function.

If a MEX function is locked, you cannot clear the MEX file. Therefore, if you attempt to clear a locked MEX file, MATLAB does not call the ExitFcn.

In Fortran, declare the ExitFcn as external in the Fortran routine that calls mexAtExit if it is not within the scope of the file.


See the following examples in matlabroot/extern/examples/mex.

Introduced before R2006a

Was this topic helpful?