Skip to content
Prev 2668 / 10988 Next

[Rcpp-devel] Pointer troubles

Hello,

Same as Dirk, I am not familiar with the OpenCL API. I can however give 
you some tips on external pointers to remove the need for some of the 
redundant code you would have to write when you directly use the R API 
for external pointers.

We have the Rcpp::XPtr template class that is parameterized by the class 
of the pointer, the XPtr object acts as a smart pointer, so can be 
passed down to whatever C++ function that needs a pointer. It also adds 
the necessary wrapping so that you can pass the object back to R as an 
external pointer.

With the XPtr class, you would write your code something like this:

SEXP getIntPointer(){
     int *test = new int; *test = 6;

     XPtr<int> retVal(test) ;
     return retVal ;
}

SEXP doubleIntPointer(SEXP test){
     XPtr<int> test2(test) ;
     return wrap( *test2 * 2 ) ;
}

You don't need intObjFinalizer because this is the same as the default 
finalizer that is shipped for free with XPtr:

template <typename T>
void standard_delete_finalizer(T* obj){
     delete obj ;
}

template <typename T, void Finalizer(T*) >
void finalizer_wrapper(SEXP p){
     if( TYPEOF(p) == EXTPTRSXP ){
	T* ptr = (T*) R_ExternalPtrAddr(p) ;
	Finalizer(ptr) ;
     }
}


You don't need int2SEXP because the XPtr constructor deals with it.

You don't need the SEXP2int because the XPtr dereferences itself to the 
actual underlying pointer class.

HTH,

Romain

Le 03/08/11 12:13, Willem Ligtenberg a ?crit :