[Rd] Memory allocation in C/C++ vs R?

Dominick Samperi djsamperi at gmail.com
Sat May 1 18:07:36 CEST 2010


On Sat, May 1, 2010 at 5:02 AM, Romain Francois
<romain.francois at dbmail.com> wrote:
>
> Simon,
>
> Le 30/04/10 20:12, Simon Urbanek a écrit :
> Thank you for these nuggets of information. It might be beneficial to
> promote them to some notes in the "Interfacing C++ code" section of WRE.

The manual is also missing information on R_PreserveObject() and
R_ReleaseObject(), useful but undocumented features that are
exploited in Rcpp to elininate the need for the ubiquitous
PROTECT/UNPROTECT macros.

> As a side note for users of Rcpp. In recent versions of Rcpp, we take
> precautions against the R error/c++ exception problem. We engage users to
> always enclose each c++ function in explicit try/catch/forward to R, and in
> Rcpp 0.8.0 (about to be released) we have macros BEGIN_RCPP / END_RCPP.

Good idea.

> So when users of Rcpp do callbacs to R, like this:
>
> Rcpp::Function rnorm( "rnorm" ) ;
> rnorm( -10 ) ;
>
> Rcpp catches the R error and c++ify it as a eval_error exception, so that it
> can be handled in terms of c++ try/catch.
>
> This is somewhat a hack due to the lack of explicit C level api for R error
> handling. http://www.mail-archive.com/r-devel@r-project.org/msg19300.html

Nice trick.

Given the use of undocumented features and the hacks, wouldn't it make
more sense to make Rcpp part of the R core, a kind of limited implementation
of CXXR?

With these hacks, along with a small change in the way R is built, it seems
like most of the C++ issues disappear. The change I am referring to is to
compile main.c (or a stub part of it) using C++ instead of C.

This would take care of the one remaining C++ issue: static initializers not
being called. Apparently this issue does not come up in most situations
because R links to packages that use C++ via the runtime system /
shared library mechanism, and this mechanism takes care of the
necessary static initialization. This may not work under all OS's
though, and building main.c using C++ would solve this problem.

Another advatage of building main.c using C++ is that R becomes
a C++ application (that just happens to be largely composed of C
modules). This would open more possibilities for R development
without requiring a complete refactoring as in the case of CXXR.

Dominick



More information about the R-devel mailing list