utobi
utobi

Reputation: 309

function pass by reference in RcppArmadillo

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?

Upvotes: 2

Views: 583

Answers (1)

Dirk is no longer here
Dirk is no longer here

Reputation: 368399

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

Upvotes: 3

Related Questions