MATLAB: Does clear mex command in StopFcn specified in Simulink Model Properties’ not unlock the MEX files and unload DLLs

dlllockmexmodelpropertiesremovesimulinkstopfcnunloadunlock

I have a Simulink model which loads a DLL and uses some mex files in simulink blocks.  When I stop the Simulation, I would like the DLL unloaded.  Using "clear mex" works for this purpose.  I put "clear mex;" in the StopFcn callback of the model so that this is done every time the Simulation stops, but it does not seem to be working.  If I execute "clear mex" from the command line after simulation ends, it does clear the mex files.
Is this incorrect use of the StopFcn callback?  How can I make the mex file clear (and thus have the DLL unloaded) after the Simulation is stopped?

Best Answer

The reason for this behavior, as the "clear mex" document points out, is that 'clear mex does not clear locked MEX functions or functions that are currently in use'. In Simulink, the MEX files are not unlocked until the model and all it's callbacks are done.
To achieve your workflow, you can explicitly force the MEX to unlock using "munlock" and then use "clear mex". Here is the example script that you can use it in the "StopFcn" of your model.
% Initially, the MEX is locked
isLocked = mislocked('mexTest.mexw64')
clear mex;
% MEX should be locked even after clearing it
isLocked = mislocked('mexTest.mexw64')
% Unlock MEX explicitly
munlock('mexTest.mexw64')
% Check if locked and then clear
isLocked = mislocked('mexTest.mexw64')
clear mex