function pass by reference in RcppArmadillo

邮差的信 提交于 2019-12-30 07:29:10

问题


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, but it's helpful in my case. Concretely, I'm trying this:

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

What am I missing ? Why is not working?


回答1:


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


来源:https://stackoverflow.com/questions/44047145/function-pass-by-reference-in-rcpparmadillo

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