Safe memory management when interfacing code via MEX
Mostrar comentarios más antiguos
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 comentario
James Tursa
el 11 de Jul. de 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.
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Startup and Shutdown en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!