function pass by reference in RcppArmadillo

后端 未结 1 1204
误落风尘
误落风尘 2021-01-07 07:01

I have a function written in RcppArmadillo style and I want to use it for changing variables in the calling environment. I know it is not advisable to do things like this, b

相关标签:
1条回答
  • 2021-01-07 07:41

    A double is not a native R type (so there is always a copy being made) and no pass-through reference is possible.

    Instead, use Rcpp::NumericVector which is a proxy for a SEXP type. This works:

    R> sourceCpp("/tmp/so44047145.cpp")
    
    R> x = 1.0  
    
    R> myfun(x) 
    Inside myfun: x = 0.0361444
    
    R> x        
    [1] 0.0361444
    R> 
    

    Below is the full code with another small repair or two:

    #include <RcppArmadillo.h>
    
    // [[Rcpp::depends(RcppArmadillo)]]
    
    //[[Rcpp::export]]
    void myfun(Rcpp::NumericVector &x){
      arma::mat X = arma::randu<arma::mat>(5,5);
      arma::mat Y = X.t()*X;
      arma::mat R1 = chol(Y);
    
      x[0] = arma::det(R1);
      Rcpp::Rcout << "Inside myfun: x = " << x << std::endl;
    }
    
    
    /*** R
    x = 1.0  // initialize x 
    myfun(x) // update x to a new value calculated internally
    x        // return the new x; it should be different from 1
    */ 
    
    0 讨论(0)
提交回复
热议问题