vendredi 3 novembre 2017

How to access a member of a C++ class exposed through an RCPP_MODULE?

I need to update the state of a member of a class, by calling a method of this member from R:

class X {           // the class of the member object
  int a_ = 0;
public:
  void increment(){
    a_++;
  }
  int a() const {
    return a_;
  }
};

class Y {
  X x_;
public:
  X& x() {      // returning a reference in order to modify x_ from outside.
    return x_;
  }
};

RCPP_EXPOSED_CLASS(X)    // needed for the property returning X& below

RCPP_MODULE(X) {
  Rcpp::class_<X>("X")
  .constructor()
  .method( "increment", &X::increment )
  .property( "a", &X::a )
  ;
}
RCPP_MODULE(Y) {
  Rcpp::class_<Y>("Y")
  .constructor()
  .property( "x", &Y::x )
  ;
}

In R:

x<-X$new()
x$a  # returns 0
x$increment() 
x$a  # returns 1

y<-Y$new()
y$x$a # returns 0
y$x$increment() 
y$x$a # returns 0 

The fact that y$x$a returns 0 and not 1 means that increment() has been called on a copy of the original object. Is it possible to invoke the method increment() on the original member x_ of y?

I've considered using a public method void increment_x() {x_.increment();} in the class Y, but this solution is not working for me.

Aucun commentaire:

Enregistrer un commentaire