[Rcpp-devel] Garbage collection PreserveObject.

Romain Francois francoisromain at free.fr
Sun Jan 24 09:18:45 CET 2010


On 01/24/2010 12:44 AM, Guillaume Yziquel wrote:
> Hi.
>
> I recently noticed that the garbage-collection interfacing toping has
> been quite active at the beginning of the month on this list, so I'm
> asking here. My question concerns essentially my OCaml binding, but I'll
> try to make it as language agnostic as possible to somehow stay within
> the scope of this list.

Here are some axioms:
- when you PROTECT, you must UNPROTECT.
- when you R_PreserveObject, you should R_ReleaseObject
- both approach are unrelated

> Two questions:
>
> -1- From what I gathered, it is fine to issue two PreserveObject
> statements on the same SEXP, and then two ReleaseObject afterwards. It
> seemed to me that reference counting was not needed, from my
> understanding of the past discussion. Am I wrong?

R_Preserve/R_Release are based on a precious pair list. when you 
R_Preserve an object, say "x",  then x is added in front of the pairlist 
(there is no check to see if the object is already in the pairlist).

when you release, it goes though the pairlist until it finds the target 
SEXP (the first time) and removes it.

so it is not really reference counting, but the only thing you have to 
do is release as many times as you protect (in whatever order you 
choose, whenever you choose)

> -2- Once you have, in your C/C++ code, obtained a pointer to a SEXP from
> R, do you need to PROTECT it, then do a PreserveObject, then UNPROTECT
> it? Or is PreserveObject simply fine? (I guess so, but I'm damn unsure).

They are totally unrelated.

As simon said on R-devel, it just is not a matter of choice. If you want 
your object to persist you use Preserve/Release. If your SEXP is local 
to function, then PROTECT/UNPROTECT will work "faster" ... however you 
can still use Preserve/Release for local objects.

Essentially, in Rcpp we only use Preserve/Release so that garbage 
collection management is implicit, automatic and hidden.

Does that help ?

Romain

-- 
Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
http://romainfrancois.blog.free.fr
|- http://tr.im/KfKn : Rcpp 0.7.2
|- http://tr.im/JOlc : External pointers with Rcpp
`- http://tr.im/JFqa : R Journal, Volume 1/2, December 2009



More information about the Rcpp-devel mailing list