[Rcpp-devel] rcpp_modules: Passing object pointer back to C++

Mr.M at gmx.at Mr.M at gmx.at
Sun Jan 22 15:43:11 CET 2012


Hello there,

I am implementing a package with rcpp_modules which basically worked fine until I tried to add a method which allows the user to do the following in R:

a = new (MyPackage::MyClass)
b = new (MyPackage::MyClass)
a.doSomething(b)

-------

The code behind looks somewhat like this:

#include <Rcpp.h>
class MyClass {
public:

  int a;

  MyClass(int a_){a = a_};

  //Option1
  void doSomething(MyClass * ref){
    return ref->a + a;
  }
  //Option2
  void doSomething(SEXP sx){
    MyClass * ref = //what to write here???
    return ref->a + a;
  }
  //End

};


RCPP_MODULE(yada) {
class_<Uniform>( "Uniform" )
.constructor<int>()
.field( "a", &MyClass::a )
.method( "doSomething", &MyClass::doSomething )
;
}

----------

So, what I am trying to do, is to get a C++ pointer to the (C++) object of the method-argument.

Option 1 does not work, because the MyClass * is not an Rcpp compatible type: 
"error: cannot convert ‘SEXP’ to ‘MyClass*’ in initialization"

With Option 2 I have not figured out, how to cast the SEXP to something useful. It definitely is a S4SXP with one slot ".xData". The contents of this slot are something like "<environment: 0x2b2f830>".

So my question now is: Is this the memory address of the C++ object?
If it is, how can I assign this address to a C++ pointer of type "MyClass *" ?
Is there any other possibility to unwrap rcpp_module's S4SXP datatypes to C++ pointers?

(I am aware that R garbage-collects the object when it goes out of scope; This is no problem in this scenario)

------

So far I have (unsuccessfully) tried:

MyClass *ref = static_cast<MyClass*> (R_ExternalPtrAddr(n));

if( TYPEOF( sx ) == S4SXP  )  MyClass* ref = (MyClass*) EXTPTR_PTR( R_do_slot( sx , Rf_install(".xData") ) ) ;

if( TYPEOF( sx ) == S4SXP  )  MyClass* ref = (MyClass*) R_do_slot( sx , Rf_install(".xData") );

Rcpp::S4 a = Rcpp::S4(sx); MyClass* ref = (MyClass*) a.slot(".xData")<MyClass*>;


The first three result in a memory error. The last one is syntactically incorrect, because I have not figured out how to correctly use the template operator of SlotProxy.

-------

A somewhat related thread is: http://lists.r-forge.r-project.org/pipermail/rcpp-devel/2011-December/003223.html

Any help is appreciated.
(The only thing that mustn't be changed is "a.doSomething(b)".)


regards, Michael

By the way... I think that rcpp_modules is a great tool and will be widely used in future.

-- 
"Feel free" - 10 GB Mailbox, 100 FreeSMS/Monat ...
Jetzt GMX TopMail testen: http://www.gmx.net/de/go/topmail


More information about the Rcpp-devel mailing list