问题
I am making a package containing two Rcpp functions. The first function is used for creating a matrix that will be used several times by the second function. The matrix is stored in R's global environment between calls to the two functions.
M <- myFirstRcpp(X)
P <- mySecondRcpp(M)
Depending on input parameters the second function will make changes to the input matrix (created by the first function) before calculating a vector from it (aFunction
is the C++ inside mySecondRcpp()
):
IntegerVector aFunction( SEXP Qin, SEXP param ) {
NumericMatrix Q(Qin);
// Some changes made to Q
...
// return a vector generated from Q
}
My problem is that the changes done to the Q
matrix inside the second Rcpp function also affect the copy of the matrix (M
) residing in R's global environment.
How can I prevent Rcpp from altering the global environment of R without too much overhead?
Notes: The M
matrix is ~2000x65000 in size. The problem occurs with R 3.0.2 and Rcpp 0.10.6 on Windows and Linux in 32 and 64 bit R.
回答1:
That is a known and documented feature. We are being called from R via the interface
SEXP somefunction(SEXP a, SEXP b, ...)
so a pointer is being passed and changes to Q
affect the outer object. That is a good thing as it makes the calls very fast -- no copies.
If you want distinct instances, use the clone()
method as in
NumericMatrix Q = clone(Qin);
回答2:
Another thing you can do from within R (e.g., when you cannot easily edit the Rcpp
code) is to call a [
method on the R object reference. This forces R to pass a copy. For example,
M <- myFirstRcpp(X)
P <- mySecondRcpp(M[])`
Now, M
will not get altered by side-effects from mySecondRcpp()
.
来源:https://stackoverflow.com/questions/21281911/how-can-i-protect-a-matrix-in-r-from-being-altered-by-rcpp