[Rcpp-devel] Persistence of C++ changes in R.

Dirk Eddelbuettel edd at debian.org
Wed Dec 22 19:32:21 CET 2010


On 22 December 2010 at 18:08, Cedric Ginestet 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;

The operator[] can only take a single argument. '1,1' happens to be an
expression with value 1, so you are getting the element with index one (and
we're zero-based here).

Use curlies instead.

| 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++?
| 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?

Pointers.  

You init xD based on D, and make a change. That reflects back on D.

Dirk

| 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

-- 
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com


More information about the Rcpp-devel mailing list