[Rcpp-devel] Best way to return raw array

Darren Cook darren at dcook.org
Fri Sep 2 03:16:49 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;
'

mysample_cpp<-cxxfunction( signature(n="numeric"), src1cpp, plugin='Rcpp')

At first I wasn't using "delete p", and it worked fine, but the memory
leak bothered me. Now I've added the delete it (irregularly) gives bad
results. E.g.
 mysample_cpp(10)
 [1]  1.00000e+01  1.00000e+01  1.00000e+01  1.00000e+01  1.00000e+01
1.00000e+01 6.74011e+199  1.00000e+01  1.00000e+01  1.00000e+01

So,
 Q1: Was there no memory leak? I.e. R has taken control of my memory
block and will delete it for me?

 Q2: Is this the best way to do it (with maximum speed, but no memory
leaks, in mind)?

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