[Rcpp-devel] Persistence of C++ changes in R.
Douglas Bates
bates at stat.wisc.edu
Wed Dec 22 19:32:18 CET 2010
On Wed, Dec 22, 2010 at 12:08 PM, Cedric Ginestet
<c.ginestet05 at googlemail.com> wrote:
> Dear Rcpp Experts,
>
> I have encountered two issues when modifying an object within C++ function.
> See the code below:
>
> ##########################################
> library(inline); library(Rcpp)
> D <- matrix(rnorm(4),2,2)
> src3 <- '
> NumericMatrix xD(D);
> xD[1,1] = 100.0;
> return xD;
> '
> passRef <- cxxfunction(signature(D="matrix"),body=src3,plugin="Rcpp")
> passRef(D); D
> ###########################################
>
> From which I get the following:
> [,1] [,2]
> [1,] -0.587375 0.3173949
> [2,] 100.000000 0.1801181
> [,1] [,2]
> [1,] -0.587375 0.3173949
> [2,] 100.000000 0.1801181
>
> I have two questions here:
> 1. Why is the [2,1] modified, when I would have expected the [2,2] entry to
> be modified, given that I had assign 100.0 to xD[1,1] in C++?
Well when I call cxxfunction on that code I get a warning. Did you?
The warning tells me that I am indexing xD as a one-dimensional array
and that leads me to believe that I probably want xD(1,1), not xD[1,1]
> 2. Why does the change to the object D persist when we call the object
> again? This looks like D has been passed by reference and is therefore
> affected by what happened within the function. However, this is not the
> expected behaviour for an R function. What's going on here?
It is the expected behavior when you pass an R object through the
.Call interface. If you want to change a copy then define
NumericMatrix xD(clone(D));
which does the deep copy operation.
> Thank you very much for your help,
> Cedric
>
>
> --
> Cedric Ginestet
> Centre for Neuroimaging Sciences (L3.04)
> NIHR Biomedical Research Centre
> Department of Neuroimaging
> Institute of Psychiatry, Box P089
> King's College London
> De Crespigny Park
> London
> SE5 8AF
> Tel: (+44) 20-3228-3052
> Fax: (+44) 20-3228-2116
> Email: cedric.ginestet at kcl.ac.uk
>
> _______________________________________________
> Rcpp-devel mailing list
> Rcpp-devel at lists.r-forge.r-project.org
> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel
>
>
More information about the Rcpp-devel
mailing list