函数在RcppArmadillo中通过引用传递 [英] function pass by reference in RcppArmadillo
问题描述
我有一个用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?
推荐答案
double
不是本机R类型(因此总是复制 ),并且没有传递引用是可能的.
A double
is not a native R type (so there is always a copy being made) and no pass-through reference is possible.
相反,请使用Rcpp::NumericVector
,它是SEXP
类型的代理.这有效:
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
*/
这篇关于函数在RcppArmadillo中通过引用传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!