0

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?

Amro
  • 123,847
  • 25
  • 243
  • 454
embert
  • 7,336
  • 10
  • 49
  • 78
  • That is the general way how mex function. did you tried to give one variable as input, modified it and see what you get after the function (without return). At least in some of the things I do it does modify the original one. – ASantosRibeiro Sep 21 '14 at 12:07
  • 1
    @ASantosRibeiro: you should never modify the input arrays. *(You could do that but you'll have to tell MATLAB to "unshare" it, that way other variables in the parent scope don't get unexpectedly modified as well. So if you have something like: `y=x; myMexFcn(x);` and you naively modify `x` inside the MEX-function, `y` will get modified as well! In other cases, there could be more dangerous consequences and it could even crash MATLAB.)* – Amro Sep 21 '14 at 13:09

1 Answers1

4

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.

Community
  • 1
  • 1
Amro
  • 123,847
  • 25
  • 243
  • 454
  • So, if one is aware of these facts there seems to be no deal. In my case I'd like to move 3 levels of a 4 level loop to mex. That would save quite an amount of code which otherwise would have to be ported to C. I assume, if a mex function is designed for a very specific case one may indeed simply cast the `const mxArray *`, since the array is created for being filled by the mex function. – embert Oct 02 '14 at 11:18
  • @embert: yes I suppose so (please read my previous comment above in response to ASantosRibeiro). After all you could do pretty much anything in C/C++, as long as you know what you're doing :) Just make sure to clearly comment the code around the MEX call to indicated this is a potentially dangerous operation that could break in future releases. You should also place the MEX file in a `private` folder next to the MATLAB function calling it, that way it is not called by anyone else causing MATLAB to crash... – Amro Oct 02 '14 at 16:56