Skip to content

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

3 messages · Christian Gunning, Romain Francois

#
To elaborate a bit:

Am I off-base in thinking you can make a custom constructor for your
class that calls R's new(), being careful to avoid circularity, that
returns a blank instance to your method to be filled? Is something
like the following anywhere near this?

class MyClass {
  public:
    Bar(bool x_) : {}  // for spawn
    Bar() : {}

  private:
    Bar spawn() {
      Environment meth("package:methods");
      Function Rnew = meth["new"];
      Rcpp::XPtr<MyClass> NewObj( Rnew(false) );
    }
};

-Christian
2 days later
#
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()
#
Le 06/06/11 06:09, Christian Gunning a ?crit :
I'm playing with this now. More later ...

Romain