Skip to content
Prev 2680 / 10988 Next

[Rcpp-devel] Pointer troubles

Q: In latex code after quote, I've highlighted the new/free/finalizer
issue (adapted from Romain).  Alternately, this code (again, Romain's)
highlights passing an SEXP to XPtr<...>.  It seems that one or the
other should be primary.

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

Comment: A concise example that uses an XPtr in a C++ function is
still lacking.  I'll look at this now+20hrs-ish.

It's been a hectic summer, sorry to reappear on list out of nowhere...
-xian
\paragraph{External Pointers}~
  \newline
<<lang=cpp>>=
// The Rcpp::XPtr template class is parameterized by the class of the
pointer.  XPtr objects are smart pointers and can be passed to C++
functions that require pointers.  XPtr objects can also be wrap()ed
and passed back to R as external pointers.

// XPtr includes a default finalizer.  Thus in this example test need
not be freed.
SEXP getIntPointer(){
    int *test = new int;
    *test = 6;
    XPtr<int> retVal(test);
    return retVal ;
}

// Define a simple function
double sumFun(SEXP xs) {
    Rcpp::NumericVector x(xs);
    double sum = std::accumulate(x.begin(), x.end(), 0.0);
    return(sum);
}

// Define a pointer to the above function
typedef double (*funcPtr)(SEXP);
ret = XPtr<funcPtr>(new funcPtr(&sumFun));
return ret;
@