MATLAB: Am I unable to completely unload a MEX-file compiled with the /CLR option to Microsoft Visual Studio 2003 or 2005 in MATLAB 7.4 (R2007a)

MATLAB

I am compiling a C++ MEX-file using a .NET-aware version of Microsoft Visual Studio, such as 2005 or .NET 2003. I have modified my MEX options to replace "/EHs" with "/EHa /CLR" in the compile-time flags.
After compiling and executing a C++ MEX-file:
mex -f myClrOptions.bat mexcpp.cpp
mexcpp(1,2)
I find that I cannot delete or overwrite the MEX-file, even after using
clear mex
to unload it from MATLAB. After using CLEAR, INMEM reports that the MEX-file is no longer in memory, but I am unable to delete or overwrite it.
Exiting MATLAB resolves the issue.

Best Answer

This is the expected behavior for Microsoft's Common Language Runtime. Managed code linked against Microsoft's Common Language Runtime cannot be unloaded from memory in the same ways as non-CLR shared libraries.
To work around this issue, you may be able to specify that your MEX-file run in a dedicated .NET AppDomain. You can find more information here:
As noted here, an AppDomain-neutral assembly (in this case, the MEX-file) cannot be unloaded without terminating the entire process (in this case, MATLAB).