Skip to content
Prev 2158 / 10988 Next

[Rcpp-devel] Creating pointers to objects and wrapping them

The vignette states that I should specialize the wrap template or 
implement the operator SEXP() for my class B. Unfortunately, it does not 
give any hint about how to create an appropriate SEXP from an arbitrary 
object pointer. After doing some research on the internet and a look at 
the Matrix package I came up with the following approach. Could 
something along these lines work at all?

#include <Rdefines.h>

SEXP foo() {
   B* b = new B(1);
   Rcpp::XPtr<B> xptr(b);
   SEXP s4_obj = PROTECT(NEW_OBJECT(MAKE_CLASS("Rcpp_B")));
   SEXP slot = Rcpp::wrap(std::string("pointer"));
   SET_SLOT(s4_obj, slot, xptr);
   UNPROTECT(1);

   return s4_obj;
}

Unfortunately, this does not work as expected. In R, the returned 
variable has type "S4", which is what I want. It cannot be used, though:
Error in get(".pointer", envir = env) : Object '.pointer' not found. 
Perhaps all that is missing is a way to correctly initialize the 
"pointer" or ".xData" of the created object. Any hints on that?

On the other hand, since I do not really understand in detail what 
happens here, the code above could also be perfect nonsense...

Best regards,
Peter