Skip to content
Prev 2156 / 10988 Next

[Rcpp-devel] Creating pointers to objects and wrapping them

Dirk,
Here is a small, abstract example which demonstrates one of the 
scenarios where I would like to create and return object pointers. There 
are two classes, A and B. Instances of A contain pointers to instances 
of B. I would like to create the B objects pointed to by A on demand, 
and query A for these. (In the actual application, both A and B are 
rather complex mathematical objects, which require a lot of work to 
compute. They are not only created and stored, but also modified, 
swapped, removed, etc.)

This is the basic idea:

// B just stores an integer i here
class B {
   public:
     B(int i) : i(i) {}

     int get_i() {
       return i;
     }

   private:
     int i;
}

// A contains a vector v of pointers to B
class A {
   public:
     A(int n) : v(n) {}

     // THIS IS THE METHOD I WOULD LIKE TO IMPLEMENT:
     SEXP foo(int j) {
       if (!v[j]) {
         v[j] = new B(j);
       }

       // THIS DOES NOT WORK:
       return wrap(v[j]);
     }

   private:
     std::vector<B*> v;
}

// Rcpp module exposing both A and B
RCPP_MODULE(MyModule) {
   class_<A>( "A" )
     .constructor<int>(
             "Create an instance of A with a given number of pointers")
     .method("foo",
             &A::foo,
             "(Create and) get one of the objects of type B.")
   ;

   class_<B>( "B" )
     .constructor<int>("Create an instance of B from an int.")
     .property("i",
               &B::get_i)
   ;
}

In R, I would then like to do, e.g., this:

a <- new (A, 5)
b <- a$foo(0)
b$i

I could rephrase the question as follows: How do I create objects of the 
exposed classes within C++ in a way which allows me to return them to R?
OK, thank you.


Best regards,
Peter





Am 17.04.2011 10:45, schrieb schattenpflanze at arcor.de: