RcppArmadillo 中的函数通过引用传递

function pass by reference in RcppArmadillo

我有一个用 RcppArmadillo 风格编写的函数,我想用它来改变调用环境中的变量。我知道做这样的事情是不可取的,但它对我的情况很有帮助。具体来说,我正在尝试这样做:

#include <RcppArmadillo.h>
#include <iostream>

//[[Rcpp::export]]
void myfun(double &x){
  arma::mat X = arma::randu<arma::mat>(5,5);
  arma::mat Y = X.t()*X;
  arma::mat R1 = chol(Y);

  x = arma::det(R1);
  std::cout << "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
*/ 

我错过了什么?为什么不起作用?

A double 不是本机 R 类型(因此 总是 正在制作副本)并且不可能传递引用。

而是使用 Rcpp::NumericVector,它是 SEXP 类型的代理。这有效:

R> sourceCpp("/tmp/so44047145.cpp")

R> x = 1.0  

R> myfun(x) 
Inside myfun: x = 0.0361444

R> x        
[1] 0.0361444
R> 

下面是完整的代码,还有一两个小修复:

#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
*/