[Rcpp-devel] Preferred idiom for obtaining a pointer in Rcpp

Dirk Eddelbuettel edd at debian.org
Tue Mar 16 03:10:13 CET 2010


On 15 March 2010 at 19:33, Douglas Bates wrote:
| I have been using the begin method to obtain a pointer to the contents
| of an Rcpp::Vector object.  For example
| 
| Rcpp::NumericVector foo(10);
| double *ptr = foo.begin();

I use that form. And we have gotten fond of the begin() notion which opens
the door to all sorts of STL niceties such as the transform() 'algorithm'.
 
| Would a preferred idiom be
| 
| double *ptr = &foo[0]:

My first instinct was that this couldn't work, but as it happens, my instinct
isn't worth much it seems. See below.

The classes are meant to be somewhat opaque and you're really supposed to
poke in like that even when it works.

Dirk

Working test below:

edd at ron:/tmp$ cat doug.r
#!/usr/bin/r -t

library(inline)
library(Rcpp)

cpp <- '
   NumericVector x(xs);
   double *p = x.begin();
   double *q = &x[0];
   for (int i=0; i<4; i++) {
      std::cout << *p++ << " " << *q++ << std::endl;
   }
   return x;
'
fun <- cfunction(signature(xs="numeric"), cpp,
                 Rcpp=TRUE, includes = "using namespace Rcpp;")
print(fun(1:4))
edd at ron:/tmp$ ./doug.r
Loading required package: methods
1 1
2 2
3 3
4 4
[1] 1 2 3 4
edd at ron:/tmp$


-- 
  Registration is open for the 2nd International conference R / Finance 2010
  See http://www.RinFinance.com for details, and see you in Chicago in April!


More information about the Rcpp-devel mailing list