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

Romain Francois romain at r-enthusiasts.com
Thu Apr 21 11:13:04 CEST 2011


Le 21/04/11 11:01, schattenpflanze at arcor.de a écrit :
>> Now, for Rcpp classes to be aware of a custom wrap, you need some
>> gymnatics, as described in the Rcpp-extending vignette.
>> You need to include RcppCommon.h first, define you class and declare the
>> custom wrap, then include Rcpp.h, then define you wrap.
>> I'm pasting a full pass at it below.
> Thanks a lot for your help!
>
>> Things will get much simpler when we figure out a way to return classes
>> exposed by modules and implement it.
> I am looking forward to that :-).

Don't hold your breath. This will need time to design and implement it 
right.

> Peter
>
>
>
>> require( inline )
>> require( Rcpp )
>>
>> settings <- getPlugin("Rcpp")
>> settings$includes <- sprintf( "%s\n%s",
>> '
>> #include <RcppCommon.h>
>> // B just stores an integer i here
>> class B {
>> public:
>> B(int i) : i(i) {}
>>
>> int get_i() const {
>> return i;
>> }
>>
>> private:
>> int i;
>> } ;
>> namespace Rcpp{
>> template <>
>> SEXP wrap( const B& object ) ;
>> }
>> ',
>> settings$includes
>> )
>>
>> inc <- '
>> namespace Rcpp {
>> template <>
>> SEXP wrap( const B& object ){
>> Language call( "new", Symbol( "B" ), object.get_i() ) ;
>> return call.eval() ;
>> }
>> }
>>
>> // 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)
>> ;
>> }
>> '
>>
>> fx <- cxxfunction( , '
>>
>> ', includes = inc, settings = settings )
>> populate( Module( "MyModule", getDynLib( fx ) ), env = .GlobalEnv )
>>
>> a <- new (A, 5)
>> b <- a$foo(0)
>> b$i
>


-- 
Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
http://romainfrancois.blog.free.fr
http://romain-francois.com
|- http://bit.ly/hdKhCy : Rcpp article in JSS
|- http://bit.ly/elZJRJ : Montpellier Comedie Club - Avril 2011
`- http://bit.ly/fhqbRC : Rcpp workshop in Chicago on April 28th




More information about the Rcpp-devel mailing list