[Rcpp-devel] Rcpp and ExternalPtr

Dirk Eddelbuettel edd at debian.org
Mon Dec 8 17:34:03 CET 2014


On 8 December 2014 at 09:58, Tim Keitt wrote:
| 
| 
| On Sun, Dec 7, 2014 at 4:52 AM, Dirk Eddelbuettel <edd at debian.org> wrote:
| 
|    
| 
|     What you are after, if I understand it correctly, is (close to) a common
|     and
|     well studied idiom called 'RAII': Resource Acquisition is Initialization.
|     Two
|     quick links, and you will find many more:
| 
| 
| 
| I don't know if this example is helpful. Any class that can be initialized with
| an SEXP and has an SEXP member function can be used as the argument or return
| type from an Rcpp function call. I wrote this wrapper to avoid dereferencing
| passed null pointers and as a return type for a lot of functions where I want
| an R NULL return if the pointer is null.

Nice post for the r-devel list :)  But as you don't use Rcpp here...

In essence Rcpp::XPtr does this for you.  If you rewrote the code in terms of
Rcpp::XPtr, it might make for a nice post for the Rcpp Gallery.

Dirk
 
| THK
| 
| 
| class 
| RGDALHandleWrapper
|                         {
|                         public:
|                         RGDALHandleWrapper(void* h)
|                         : handle(h) {} // If initialized NULL will return NULL
|                         SEXP
|                         RGDALHandleWrapper(const SEXP h)
|                         : handle(R_ExternalPtrAddr(h))
|                         {
|                         if ( !handle ) stop("Null pointer passed to function\n"
|                         );
|                         }
|                         operator SEXP() const
|                         {
|                         return handle ? // Return NULL SEXP on NULL pointer
|                         R_MakeExternalPtr(handle, R_NilValue, R_NilValue) :
|                         R_NilValue;
|                         }
|                         void* operator*() const { return handle; }
|                         private:
|                         void* handle;
|                         };
| 
|  
| 
| 
| --
| http://www.keittlab.org/

-- 
http://dirk.eddelbuettel.com | @eddelbuettel | edd at debian.org


More information about the Rcpp-devel mailing list