Search code examples
cmatlabmexdeep-copycopy-on-write

Does Matlab ever copy data passed to a mex function?


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?


Solution

  • 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.