From djsamperi at gmail.com  Sat May  1 18:07:36 2010
From: djsamperi at gmail.com (Dominick Samperi)
Date: Sat, 1 May 2010 12:07:36 -0400
Subject: [Rd] Memory allocation in C/C++ vs R?
In-Reply-To: <4BDBEE2B.8020103@dbmail.com>
References: <m2qd4cf43b61004292203x8265d834wb1d42c483813d55d@mail.gmail.com>
	<491D8740-466D-4442-B6BE-942A9C423CD0@r-project.org>
	<u2vd4cf43b61004301040jc5a99578k9b44b41e7b414b0a@mail.gmail.com>
	<F58D45DC-69AB-43C5-B6E4-CE5C87354DBE@r-project.org>
	<4BDBEE2B.8020103@dbmail.com>
Message-ID: <AANLkTimPA3WjWi4TWbrnE8TtKV6r651jsPZdQWXk4b59@mail.gmail.com>

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



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