[Rcpp-devel] Create an instance of a reference class for a C++ class exported as a module from within C++?

Romain Francois romain at r-enthusiasts.com
Mon Jun 6 14:44:59 CEST 2011


Le 06/06/11 06:09, Christian Gunning a écrit :
>> At the moment the only way i see is to make an R call to "new" and construct the object this way...
>
>>> Many of the methods for this class return other members of this class.
>>> Can I create a new instance of the reference class in R from within
>>> the module?  I'm sure it is possible, I'm just wondering if there is
>>> an easy way to do this without duplicating large chunks of the code in
>>> Rcpp/src/Module.cpp.  Can i somehow clone the SEXP representing the
>>> current instance then swap the external pointer to the C++ object?
>
> I played with this a little more, and the following works fine.
> Nothing striking here. The part I don't understand is, can you employ
> the SEXP returned by spawn() as an instance of Bar, or are you then
> stuck with the R interface to Bar?
>
> -Christian
>
> ## in R
> Rcpp.package.skeleton('testmod', module=T)
>
> //in testmod/src/rcpp_module.cpp
>
> #include<Rcpp.h>
> using namespace Rcpp;
> class Bar {
> public:
>      Bar()  {}
>      void set(int state_) { this->state = state_; }
>      int get() { return state; }
>
>      SEXP spawn() {
>          Environment meth("package:methods");
>          Function Rnew = meth["new"];
>          Function Rget("get");
>          SEXP NewObj( Rnew(Rget("Bar")) );
>          return NewObj;
>      }
> private:
>      int  state;
> };
>
> ## in R
> require(testmod)
> bb = new(Bar); bb$set(3)
> cc = bb$spawn();  cc$set(4)
> bb$get(); cc$get()

I'm playing with this now. More later ...

Romain

-- 
Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
http://romainfrancois.blog.free.fr
http://romain-francois.com
|- http://bit.ly/kaSV6U : Stand up set at Up The Creek
|- http://bit.ly/hdKhCy : Rcpp article in JSS
`- http://bit.ly/elZJRJ : Montpellier Comedie Club - Avril 2011




More information about the Rcpp-devel mailing list