[Rcpp-devel] wrapping a class having a method returning an object of class-type

Dirk Eddelbuettel edd at debian.org
Thu May 31 21:00:00 CEST 2012


Hi James,

On 31 May 2012 at 09:42, James Simone wrote:
| I have a C++ class that has a "clone" method which returns a distinct copy of the object.
| I want to expose the clone method in R and my question is how this is best done using Rcpp?
| 
| My first attempt to expose "clone" results in a compile error since Rcpp cannot automatically handle
| the returned object. Consider an example,
| 
| class Cnorm
| {
| public:
|    Cnorm() : z(0) {}
|    Cnorm(double z_) : z(z_) {}
|    double operator()( double x, double y ) const { return sqrt( x*x + y*y + z*z ); }
|    Cnorm clone() const { return Cnorm(z); }
| private:
|    double z;
| };
| 
| RCPP_MODULE(mod) {
|    using namespace Rcpp;
|    class_<Cnorm>("Cnorm")
|      .constructor<double>("constructor")
|      .method("clone",&norm::clone,"clone this object")
|      .method("norm",&Cnorm::operator(),"take the norm");
| }
| 
| I found a solution which seems to work which involves adding
| a free function. I have two questions, however,
| 
| 1) Is the workaround below reasonable/best?
| 2) Does Rcpp properly take ownership of the new'ed Cnorm object?
| 
|   SEXP cloner(Cnorm* self) {
|    Cnorm* cpy = new Cnorm;
|    *cpy = self->clone();
|    return  Rcpp::internal::make_new_object(cpy);
| }

I don't think you are suppose to call something from the 'internal'
namespace.  

Moreover, make_new_object() uses Rcpp::XPtr, and I think you could just
instantiate an Rcpp::XPtr object directly. (And you'd own the memory on that,
being an external pointer -- so you may or may not return that to R.)

I have the feeling that you are trying too much at once. It might be simpler
to start with as<>() and wrap() implementations --- see the Rcpp-extending
vignette so that Rcpp and your Cnorm class get converters.  You could always
come back to Rcpp modules afterwards...

Hth,  Dirk 

| RCPP_MODULE(mod) {
|    using namespace Rcpp;
| 
|    class_<Cnorm>("Cnorm")
|      .constructor<double>("constructor")
|      .method("clone",&cloner,"clone this object")
|      .method("norm",&Cnorm::operator(),"take the norm");
| }
| 
| _______________________________________________
| Rcpp-devel mailing list
| Rcpp-devel at lists.r-forge.r-project.org
| https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

-- 
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com  


More information about the Rcpp-devel mailing list