Does Matlab ever copy data passed to a mex function?

被刻印的时光 ゝ 提交于 2019-12-23 04:57:29

问题


Concerning lazy copying: Will Matlab ever copy data passed to a mexFunction, which modifies it?

For instance in

myMex(input1(:,:,ii), input2(:,:,ii))

can one be sure, that the input matrices are never copied, so that one can pass something in and modify it, without having to return a reference?


回答1:


In certain cases, MATLAB implements some optimizations to avoid copying data when calling functions.

With MEX-functions, the input as passed as const mxArray *prhs[] (prhs is an array of pointers to constant data). Even though it is possible to change input variables without making copies (by casting away the constant-ness), it is dangerous and not officially supported, and could yield unexpected results and even segfaults (on the account of the copy-on-write technique). The official answer is to duplicate the input array, and return the modified array.

If you are willing to use undocumented features, see the mxUnshareArray and the like.. Here is an article by Yair Altman that explains this in more details.



来源:https://stackoverflow.com/questions/25958863/does-matlab-ever-copy-data-passed-to-a-mex-function

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