Matlab variables display reference-like behavior when copying and transferring to mex file

I have a mex file (compiled in VS2010, Matlab 2010b) that accepts a variable and changes it. For example, in the mex file, it looks like this:

double *fp = (double *)mxGetPr (prhs[0]); *fp = someDoubleValue; 

To compare the Matlab implementation and the mex implementation, I make a copy of the variable before calling the mex file:

 var_mex = var; mymex (var_mex); 

To my surprise, both var_mex and var change (to the same value), as if I created a link to var , not a copy of it.

Is this a known issue? How can I convince Matlab to copy a variable?

EDIT

Since I suspected that this problem was the result of Matlab optimizing memory management, I did some β€œdo nothing” calculations on var before calling the mex file, i.e.

 var=var+1; var=var-1; 

and indeed, he solves the problem. Anyway, I would be glad to receive some information (or other suggestions) about this if someone also came across it.

+6
source share
2 answers

In MATLAB, most variables are passed as if they were passed by value. A notable exception is that class instances that inherit from handle are explicitly passed by reference.

Here is a blog post that details this.

So when you do

 var_mex = var; 

You end up with var_mex referring to the same data as var .

When you write mxArray inside the mex function, you have a great chance to disrupt because you are given the base address of the data. If you change the element in the prhs array, you may inadvertently end up changing other variables sharing the same data. Therefore, do not do this. In fact, the mex doc explicitly tells you not to.

The reason the var + 1 trick works is because by modifying the data, you force MATLAB to make a copy of the data.

+7
source

All variables in Matlab are passed by value.

Making any changes directly to the rhs arguments in the mexfunction Matlab is not officially supported. If you convert the Matlab function of the form A = func(A) , then you are "obligated" to make a copy of the passed array A inside the mexfunction itself.

0
source

Source: https://habr.com/ru/post/906747/


All Articles