Can Rcpp expose a C ++ class method, referring to the same class?

Is it possible to use Rcpp to map a C ++ class to R when the class has a member that accepts an instance of this class?

Example:

#include <Rcpp.h> class Test { public: Test(int x): x_(x) {} int getValue() { return x_; } void addValue(int y) { x_ += y; } void merge(const Test& rhs) { x_ += rhs.x_; } private: int x_; }; using namespace Rcpp; RCPP_MODULE(mod_test) { class_<Test>("Test") .constructor<int>("sets initial value") .method("getValue", &Test::getValue, "Returns the value") .method("addValue", &Test::addValue, "Adds a value") .method("merge", &Test::merge, "Merges another Test into this object") ; } 

Unfortunately, this leads to the following error:

error: no matching constructor to initialize 'Test'

After reading and searching for answers, I came up with an idiom separately, including RcppCommon.h, and then inserting the block as follows:

 namespace Rcpp { template <> Test as( SEXP x ) ; } 

Unfortunately, this leads to the following errors:

Error in dyn.load ("/.../sourceCpp_86871.so"): Unable to load shared object '/.../sourceCpp_86871.so':
dlopen (/.../sourceCpp_86871.so, 6): Symbol not found: __ZN4Rcpp2asI4TestEET_P7SEXPREC Link to: /.../ sourceCpp_86871.so Expected in: flat namespace in /.../sourceCpp_86871.so

Can this be done?

Is there an implementation for the “how” specialization that I need to create? Is there an example somewhere how to write it?

As an alternative, there is an example of how to test and convert SEXP back to a C ++ object that it wraps?

+7
c ++ r rcpp
source share
1 answer

The correct as conversion seems to be generated by inserting RCPP_EXPOSED_CLASS .

Full working example:

 #include <Rcpp.h> class Test { public: Test(int x): x_(x) {} int getValue() { return x_; } void addValue(int y) { x_ += y; } void merge(const Test& rhs) { x_ += rhs.x_; } private: int x_; }; using namespace Rcpp; RCPP_EXPOSED_CLASS(Test) RCPP_MODULE(mod_test) { class_<Test>("Test") .constructor<int>("sets initial value") .method("getValue", &Test::getValue, "Returns the value") .method("addValue", &Test::addValue, "Adds a value") .method("merge", &Test::merge, "Merges another Test into this object") ; } 

Now it works correctly:

 > Rcpp::sourceCpp('test.cpp') > a = Test$new(2) > b = Test$new(3) > a$getValue() [1] 2 > a$merge(b) > a$getValue() [1] 5 
+7
source share

All Articles