Skip to content
Prev 2435 / 10988 Next

[Rcpp-devel] [Rd] Interfacing a C++ class

Le 04/06/11 16:31, soeren.vogel at uzh.ch a ?crit :
Hello,

A C++ class that is exposed through an Rcpp module is already a 
reference class, and so you can add methods, etc ...

Consider this example :

require(inline)
require(Rcpp)

fx <- cxxfunction( , '', includes = '

class FOO{
public:
     FOO( double x_, double y_): x(x_), y(y_){}

     double x ;
     double y ;

     void move( double dx, double dy){
         x += dx ;
         y += dy ;
     }
} ;

RCPP_MODULE(mod){

     class_<FOO>("FOO" )

         .constructor<double,double>()

         .field( "x", &FOO::x )
         .field( "y", &FOO::y )

         .method( "move", &FOO::move )
         ;
}


', plugin = "Rcpp" )
mod <- Module( "mod", getDynLib(fx),mustStart = TRUE )

# grab the exposed C++ class
FOO <- mod$FOO

# add R methods
FOO$methods(
     bla = function() x+y,
     reset = function() {
         x <<- 0.0
         y <<- 0.0
     }
)
# create an instance
f <- new( FOO, 2.0, 3.0 )

# call an R method
f$reset()

# call a C++ method
f$move( 2.0, 2.0 )

# call an R method
f$bla()


Hope this helps.

Romain