[Rcpp-devel] Best way to return raw array

Darren Cook darren at dcook.org
Sat Sep 3 03:51:31 CEST 2011


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

> What puzzles me is why Darren's original version doesn't work.

Due to an embarrassing bug in my test code: delete should be delete[].

So, I think we can say these two idioms are equivalent:
  NumericVector ret(p,p+nn);

  NumericVector ret(nn);std::copy(p, p + nn, ret.begin());

But, I still had one bug. [1] is my buggy code. It compiles fine, and
works fine:

> mysample_cpp(10)
[1] 10 10 10 10 10 10 10 10 10 10

But then when I run it again:

> mysample_cpp(10)
[1] 10 20 20 20 20 20 20 20 20 20

For any C++ newbies still reading, this is why using STL classes is
recommended over dealing with memory directly. STL is like the weaving
path through the woods, and new/delete are like that tempting shortcut.

(If you don't see the bug, it is because even though "new double"
initializes memory, "new double[]" does not! See my post in the "First
foray into Rcpp and comparison of speed with R" thread for a fixed version.)

Darren



[1]:

library(inline);
library(Rcpp);

src1cpp<-'
int nn=as<int>(n);
double *p=new double[nn];
for (int i=0; i<nn; i++) {
    double *q=&p[i];
    for (int j=0; j<nn; j++) {
        *q=*q+1;
    }
};
NumericVector ret(p,p+nn);delete[] p;   //OK
//This is also OK:
//NumericVector ret(nn);std::copy(p, p + nn, ret.begin());delete[] p;
return ret;
'
mysample_cpp<-cxxfunction(signature(n="numeric"),src1cpp,plugin='Rcpp')



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