Mex dynamic memory management issue with std::vector in linked external DLL; Segmentation error

∥☆過路亽.° 提交于 2019-12-06 18:16:25

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 :

You are probably seeing an incompatibility between the stl library and or compiler options used by your pre-compiled dll and those used by MATLAB and the MEX command. MATLAB 2009b was built with MSVC 2005.

You may be able to fix the problem by changing the options used by mex or by building your mex file directly with MSVC. One example of an option that may effect things is SECURE_SCL=0. I would start by building your test program with the options MATLAB is using to find the problematic option then try removing that option when building the mex file.

Because of this sort of incompatibility use of stl objects in the api's of third party compiled libraries is usually a bad idea.

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.

The MEX API doesn't do anything special with STL containers, since they cannot be passed between MATLAB and a MEX-function (the only non-primitive data type that can do that is the mxArray). It's basically up to the MEX-function to make sure that the memory used by the STL container is handled properly; MATLAB doesn't track it.

Passing a std::vector across a DLL boundary is somewhat tricky. I'd assume the vendor would be aware of this, and provide you with an appropriate header file with the correct declspecs and such, but in case they didn't, you might want to refer to this Microsoft support link to read more about what is required.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!