Mex dynamic memory management issue with std::vector in linked external DLL; Segmentation error
Show older comments
Hi there,
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<string>, 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(?), 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.
1 Comment
Kaustubha Govind
on 13 Jun 2011
AFAIK, MATLAB memory management is only used for data created using the mxArray API (for eg. mxCreateDoubleMatrix) - so the std::vector returned by your DLL should not be affected by this unless you are somehow returning the pointer to the std::vector data back to MATLAB (or setting it on an mxArray). As requested by Jan, please provide more details.
Accepted Answer
More Answers (1)
Dan P
on 13 Jun 2011
Categories
Find more on Call C++ from MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!