Safe memory management when interfacing code via MEX
조회 수: 20 (최근 30일)
이전 댓글 표시
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
James Tursa
2023년 7월 11일
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.
채택된 답변
Philip Borghesani
2015년 6월 23일
편집: Philip Borghesani
2015년 6월 23일
Locking the mex file is only needed to preserve static data. Any memory allocated using malloc or new will persist until deleted or matlab exits even if your mex file is unloaded and reloaded.
Use of mxMalloc is only* need to prevent leaks in c (or c style) code that throws exceptions via mexErrMsgIdAndTxt ether directly or indirectly.
*The other not recommended need is when the pointer will be passed to mxSetData or related functions.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Startup and Shutdown에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!