How can I protect a matrix in R from being altered by Rcpp?

亡梦爱人 提交于 2019-12-10 23:30:41

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!