I am trying to create a mex file that interfaces MATLAB with an external C++ library that communicates with some hardware. An imported library and precompiled DLL (.lib and .dll) are provided by the hardware vendor for my version of VC++ and I was able to implement them in C++ without any issue.
However, I ran into segmentation error at run time when the code is written as a mex(compiled with the same version of VC++). After some investigation with the VC++ debugger, the likely culprit seems to be the fact that one of the external dll functions returns the data type std::vector, and probably tries to dynamically allocate memory for the vector container somewhere inside the function. I know that if I use std::vector in my own mex function, everything works fine, but I suspect that the mex header itself wraps the std::vector container in my own code for memory management(?) as required for all dynamically allocated memory in mex codes, whereas it can’t do the same for the pre-compiled .dll.
Now the question is: since I cannot modify the external .dll file and have no access to its source files, are there any ways to work with this external dll such that the dynamic memory becomes managed by MATLAB(perhaps a wrapper of some sort..?)…and thereby avoid the segmentation error and return the correct data? Or if my analysis is wrong please correct me too!
Please let me know if there are any ideas or hacks, thanks!
My system: Windows 7 SP1 32 bit, MATLAB 2009b, Visual C++ 2008 Pro.
I also posted the same question at:
http://www.mathworks.com/matlabcentral/answers/9294-mex-dynamic-memory-management-issue-with-std-vector-in-linked-external-dll-segmentation-error
.You also can share your insights there if you have an account, thanks!
Thanks everyone for the answers and comments. I was able to resolve the issue with some help from the friendly folks at MathWorks.
From the original post at http://www.mathworks.com/matlabcentral/answers/9294-mex-dynamic-memory-management-issue-with-std-vector-in-linked-external-dll-segmentation-error :
Following his advice, I removed the SECURE_SCL=0 option from the mex options file at
C:\Users\(username)\AppData\Roaming\MathWorks\MATLAB\R2009b\mexopts.bat
Then recompiled the mex file, now everything works like a charm – the function is returning the correct data and segmentation error no longer occurs.