[Rcpp-devel] returning array from C

Douglas Bates bates at stat.wisc.edu
Tue Jun 11 17:58:22 CEST 2013

On Tue, Jun 11, 2013 at 10:51 AM, Steve Jaffe <sjaffe at riskspan.com> wrote:

> Is there a way to 'wrap', say, an array of double allocated on the heap in
> C/C++ and return it to R without copying, ie as the data inside a REALSXP?

I don't know of any way of doing that.  R is very possessive about memory
and expects to be able to garbage-collect any memory allocated in an

> (Let's say for example that this array allocation is in a 3rd-party
> library which can't be modified)
> Looking at the 'wrap' code it appears that copying is done in all cases
> (except for the 'external pointer').

Yes.  The only way to avoid copying is if the external library allows
objects to be constructed from pre-allocated memory.  This is used in the
RcppArmadillo and RcppEigen packages.

> Clearly the memory ownership issue is one that would need to be handled.
> Handing over ownership to R would seem the simplest approach. But it would
> be more interesting to be able to integrate with something like
> boost::shared_array so that the lifetime would be correctly managed across
> both the C and R environments.
> I've read through Rcpp documentation and "Writing R Extensions" without
> coming up with a good answer, but I'm new to this and I suspect someone
> familiar with R internals (unlike me) would immediately see what was
> involved.
> Thanks for your help.
> Steve
> _______________________________________________
> 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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20130611/15441344/attachment.html>

More information about the Rcpp-devel mailing list