[Rcpp-devel] Best way to return raw array

Darren Cook darren at dcook.org
Fri Sep 2 04:10:15 CEST 2011


> | I've extended Christian Gunning's speed test with an STL and C/C++ 
> | version; I was about to post but then I got a bit stuck with using 
> | Rcpp::wrap() for a raw block of memory. I'm using this: | |
> src1cpp<-' | int nn=as<int>(n); | double *p=new double[nn]; | ... |
> NumericVector ret(p,p+nn); | delete p; | return ret; | '
> 
> That strikes me as plain wrong code.

Hello Dirk,
Perhaps I can squeeze an answer out of you by changing it to this:

double *p=third_party_function(nn);
NumericVector ret(p,p+nn);
delete p;
return ret;

where third_party_function() is C legacy code that is documented as
returning a block of memory of size nn that the client should take
ownership of.

How do I return it?

(I took a look at the convolve examples but they all build up the result
in a Rcpp object. I cannot see an example where you have the result
ready-made in a block of memory and just need to return it.)

> c) The whole point of what we do with Rcpp is to NOT have to deal
> with new / delete and or malloc / free.  Even if you think it's cool
> and know how to it in plain, it is simply against the whole spirit
> ...STL idioms are really much better.

You'll enjoy my timing post then (as the STL does not just equal the raw
array version, it beats it).

But I think we see the raison d'etre of Rcpp differently; for me it is:
  * Optimizing key R code;
  * Interfacing with 3rd party C/C++ libraries;
  * Doing the above two while bypassing the ugly verbose code of the
usual way to write R extensions.

Or, in a sound bite: "Rcpp is not just for C++ newbies" ;-)

Darren

-- 
Darren Cook, Software Researcher/Developer

http://dcook.org/work/ (About me and my work)
http://dcook.org/blogs.html (My blogs and articles)


More information about the Rcpp-devel mailing list