[Rcpp-devel] Rcpp and ExternalPtr

Romain François romain at r-enthusiasts.com
Fri Dec 5 09:54:46 CET 2014

You are looking for XPtr. https://github.com/RcppCore/Rcpp/blob/master/inst/include/Rcpp/XPtr.h

It is a template class whose first parameter is the class of the raw pointer you are dealing with, let’s call it T. 

You can create an external pointer using something like : 

XPtr<T> xp( new T(...) ) ;

This registers the default finalizer (which calls delete) to be executed when R garbage collects the R object. So you can send xp back to the R side. 

Then you can grab it back on the C++ side, e.g. as a parameter to a function: 

// [[Rcpp::export]]
void foo( XPtr<T> xp ){
  // here you can treat xp as a raw pointer, e.g. do xp->foo( ... ) ;

You can also set the finalizer yourself with a bit more work if you wanted to do something different than the default, e.g. 

void my_finalizer( T* obj ){
   // whatever you need to do

typedef XPtr<T, PreserveStorage, my_finalizer> Bar ;

If you deal with a pointer that you don’t own, i.e. you don’t handle its finalization for some reason, you can set the second parameter of the XPtr constructor from https://github.com/RcppCore/Rcpp/blob/master/inst/include/Rcpp/XPtr.h#L84

XPtr<T> xp( raw_ptr, false ) ;


> Le 5 déc. 2014 à 08:45, Jeroen Ooms <jeroen.ooms at stat.ucla.edu> a écrit :
> Does Rcpp provide some elegant way to let the R user manage persistent
> c++ objects that have no R type (e.g. internal handles or sessions of
> some sort)?
> In C, I would use R_MakeExternalPtr to create a ptr SEXP that the user
> can pass from one R function to another. This also makes it easy to
> add a finalizer with R_RegisterCFinalizerEx so that the garbage
> collector will automatically clean up the session/handle whenever user
> deletes the R object.
> Most Rcpp examples I have seen use function arguments with standard
> data types that are automatically mapped to R types. Does Rcpp have
> any special mechanics for managing external objects (pointers) from R
> which do not map to a SEXP type? Or do I have to fall back on
> Rinternals for this?
> _______________________________________________
> 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

More information about the Rcpp-devel mailing list