[Rcpp-devel] Rcpp modules take 2, exposing C++ classes to R

Romain Francois romain at r-enthusiasts.com
Wed May 26 16:39:24 CEST 2010


Hello,

On top of exposing C++ functions (see 
http://permalink.gmane.org/gmane.comp.lang.r.rcpp/354), I've added some 
code to expose c++ classes to the R level. This is also inspired from 
boost.python (although much less comprehensive).


Consider this simple c++ class :

class World {
public:
     World() : msg("hello"){}
     void set(std::string msg) { this->msg = msg; }
     std::string greet() { return msg; }

private:
     std::string msg;
};



Using Rcpp modules, you can expose it to R, at the expense of this piece 
of code:

RCPP_MODULE(yada){
	using namespace Rcpp ;
	
	class_<World>( "World" )
		.method( "greet", &World::greet )
		.method( "set", &World::set )
	;
}


This creates an Rcpp module called "yada" that exposes the "World" class 
to R. On the R side, you then grab the module and extract the class :


yada <- Rcpp:::Module( "yada", getDynLib( fx ) )
World <- yada$World

And then you can create instances of World using the new function in R:

w <- new( World )

And then call methods :

 > w$greet()
[1] "hello"

 > w$set( "hello world" )

 > w$greet()
[1] "hello world"


This is probably the craziest c++ code I've ever written, but using it 
is easy.



There are many things boost.python does and Rcpp modules does not.

- For now -- until I find a way -- new uses the default constructor. 
Boost.Python allows other constructors to be exposed, but I'm not sure 
how to achieve this.

- no polymorphism. methods are stored in a map, so if you give the same 
name to two c++ functions, the second one will win.

- currently limited to member functions of the target class, e.g. see 
the second argument: &World::greet, etc ... I am planning to add the 
possibility (should be easy) to attach regular functions which take a
pointer to Foo or a reference to Foo.

- inputs and outputs still need to follow the rules of the last email. 
output type can be void or whatever type that Rcpp::wrap is happy with.
input types can be void or whatever sequence of types (up to 65 
arguments) Rcpp::as is happy with.

- currently no support for fields or properties.


The most obvious client to this will be the RProtoBuf package, it 
already had quiet a diet when we introduced the RCPP_FUNCTION_, etc .. 
macros, but with this the code is likely to get more simple and more robust.


Have fun.


Romain

-- 
Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
http://romainfrancois.blog.free.fr
|- http://bit.ly/cork4b : highlight 0.1-8
|- http://bit.ly/bklUXt : RcppArmadillo 0.2.1

`- http://bit.ly/936ck2 : Rcpp 0.8.0



More information about the Rcpp-devel mailing list