[Rcpp-devel] Passing arguments by value: unexpected behaviour

Romain Francois romain at r-enthusiasts.com
Tue Sep 14 11:14:22 CEST 2010


Le 14/09/10 10:55, Johannes Egner a écrit :
> Hello all,
>
> Still taking my first steps

Welcome !

> , I've come across a feature (?) I cannot yet
> make sense of. Consider a simple function with its argument passed by value:
>
> SEXP fun(SEXP arg)
> {
> using namespace Rcpp;
>
> NumericVector vec(arg);
> for(int i=0; i<vec.size(); i++)
> vec[i] += 1;
>
> return vec;
> }
>
> The call in R is declared as
>
> R.fun <- function(arg)
> {
> .Call( "fun", as.double(arg), PACKAGE = "wonderland" )
> }
>
>
> Using Rcpp 0.8.6 and R-2.11.1, I get
>
>  > arg <- 1:2 # or any vector of size > 1
>  > result <- R.fun(arg)
>  > result; arg
> [1] 2 3
> [1] 1 2
>
> That's fine -- but if I take as argument a vector of size 1, I get
>
>  > arg <- 1
>  > result <- R.fun(arg)
>  > result; arg
> [1] 2
> [1] 2
>
> What am I missing?
> Thanks, Jo

Hi,

You are missing that :

 > typeof( 1:2 )
[1] "integer"

So as.double creates a new numeric vector, but:

 > typeof( 1 )
[1] "double"

So as.double just returns its input. as.double is a primitive function 
in R, so it does not really have pass by value semantics.

By design, when you create an Rcpp object, you don't get a copy of the 
original object, you point to the same SEXP. If you want a copy, you can 
use clone, as in :

NumericVector vec = clone<NumericVector>(arg)

Romain

PS: See also 
http://lists.r-forge.r-project.org/pipermail/rcpp-devel/2010-May/000712.html 
for another manifestation of the same problem and maybe more clues.


-- 
Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
http://romainfrancois.blog.free.fr
|- http://bit.ly/cCmbgg : Rcpp 0.8.6
|- http://bit.ly/bzoWrs : Rcpp svn revision 2000
`- http://bit.ly/b8VNE2 : Rcpp at LondonR, oct 5th




More information about the Rcpp-devel mailing list