MEX is the framework Matlab uses to run C/C functions in Matlab (runs faster). In the documentation it says:
input parameters (found in the prhs array) are read-only; do not modify them in your MEX file. Changing data in an input parameter can produce undesired side effects.
Is this simply a warning about how changing a variable passed as a pointer will change that variable even outside of the function (unlike how Matlab works), or is there a more subtle way that this can mess up the Matlab/MEX interface?
Reason I am asking is I specifically want the MEX function to modify the arguments for real.
CodePudding user response:
MATLAB uses lazy copying, which means that when you do b = a
, variable b
points to the same data as variable a
, even though semantically you made a copy. When you now do a(1) = 0
, for example, you modify variable a
, and MATLAB first makes a copy, so that variable b
is not affected by the assignment. This obviously saves a lot of memory, because many copies are made where the copy is not modified.
For example, when calling a function, a copy of input variables are placed in the function’s workspace. sum(a)
causes a (lazy) copy of a
to be made available inside the function. If the function doesn’t need to modify the variable, a copy is avoided. If it does modify it, then a copy is made so that a
is not changed for the caller.
MEX-files work the same way, except that MATLAB cannot detect if you modify the input variable, so it cannot make the copy before you do. Hence the warning. You need to call mxDuplicateAreay
to copy the array and make changes to your new copy.
The side effects that the documentation warns about is that the variable in the caller’s workspace is modified, along with all variables that it shares data with. For example imagine you make a MEX-file function modifyIn
that modified the input, then:
a = zeros(500);
b = a;
% much later in the code…
modifyIn(b); % update b the way I want!
will very unexpectedly also modify a
!
This blog post on Undocumented MATLAB talks about this issue in more detail, and talks about mxUnshareArray()
, an undocumented function that you should only use if you are really comfortable with the possible crashes and other issues that could happen. Undocumented functions have a limited shelf life.