Safe memory management when interfacing code via MEX
Afficher commentaires plus anciens
I am using MEX to interface to C/C++ code, which includes the creation of objects that will outlive the call to the MEX-function. These objects will eventually be deallocated by subsequent calls to the MEX function. That is, there is persistent memory in the MEX-function.
If I understand things right, I can increase a lock counter using mexLock whenever memory is allocated in my wrappers using either C "malloc" or C++ "new" and then decrease the lock counter using mexUnlock whenever I free objects using C "free" or C++ "delete". That will prevent the MEX function to be released while the function is still in use.
Is this safe usage? I have read that one should always use mxMalloc/mxFree instead of malloc/free, but when interfacing code, this is not an option.
1 commentaire
James Tursa
le 11 Juil 2023
Yes this is not only safe, but necessary to prevent memory leaks. The other thing you can do is use a mexAtExit( ) function to free all your dynamically allocated memory when the mex function is cleared.
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Startup and Shutdown dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!