From romain at r-enthusiasts.com  Sat May  7 11:15:37 2011
From: romain at r-enthusiasts.com (Romain Francois)
Date: Sat, 07 May 2011 11:15:37 +0200
Subject: [Rd] Create and access several instances of a C++ class from R
In-Reply-To: <E7B857D5-FA61-4215-838F-88F79CACADD6@uzh.ch>
References: <49517500-0069-4F75-81E5-DAFFA2F53C08@uzh.ch>	<19908.38110.411719.560626@max.nulle.part>
	<E7B857D5-FA61-4215-838F-88F79CACADD6@uzh.ch>
Message-ID: <4DC50DB9.8090300@r-enthusiasts.com>

Hello,

Try having do_bar with this signature:

void do_bar(NumericVector data);

And my advice would probably also to have your C field either as a 
NumericVector. NumericVector is just a thin wrapper around the internal 
R data structure.

Having data members as direct pointers is dangerous and not a very C++ 
way of doing things.

If you want to learn about the STL, there are many books that cover it 
and plenty of online resources. I use this : 
http://cplusplus.com/reference/stl/. Using the STL is easier than 
dealing with pointers and stuff.

If your game is to pass down a double* to some api you use, you can use 
the begin method of NumericVector, this will give you the array pointer 
(as would REAL do on the underlying SEXP):

Here's an example:

require( Rcpp )
require( inline )

inc <- '

     // some third party api function
     double foo( double* data, int n){
         double sum = 0.0 ;
         for( int i=0; i<n; i++){
             sum += data[i] ;
         }
         return sum ;
     }
'

fx <- cxxfunction( signature( x_ = "numeric" ), '

     NumericVector x(x_) ;

     double sum = foo( x.begin(), x.size() ) ;

     return wrap( sum ) ;

', includes = inc, plugin = "Rcpp" )


I hope this helps, please send other Rcpp questions to the Rcpp-devel 
mailing list, where you have more chances to have replies. As an 
example, I don't follow R-devel as much as I would like to these days.

Romain

Le 07/05/11 10:41, soeren.vogel at uzh.ch a ?crit :
>
> Hello
>
> Thanks again for help!
>
> We have attached version info, code, and contents of 00install.out at the end of the message. The package can be found here:
>
> http://sovo.md-hh.com/files/Foo.tar.gz
>
> We had followed Dirks explanation in the Rcpp modules vignette and the presentation of Rcpp modules. The steps there and the ones Dirk listed here are basically the same, and all worked fine for us, so far. Even more, we have adapted some of the example code to a class Foo with two methods of interest, do_foo() and do_bar(). We have played around with various combinations of which method to expose in the module. In the end, exposing do_foo() works, R CMD CHECK does not complain. (Except for some namespacing error, but the same happens when I compile the example "simple", see below.)
>
> Anyway, if we want the method do_bar() to expose, R CMD CHECK Foo stops with an error that says: "cannot convert ?SEXPREC*? to ?double*? in initialization". We *guess* that it is pointers as arguments in methods exposed that cause errors, because there is no wrappers "as()" and "wrap()" for pointers in Rcpp. Indee, we know that our crystal ball may fool us.
>
> Summarising so far, principally, Rcpp modules works for us and coding with this module is very easy, especially with the help files provided in the package. However, Rcpp modules does not work if you want to expose methods with pointers as exposed methods' arguments (we assume). Yet, we have to use pointers, and rewriting the complete class is no option.
>
> Recently, Dirk gave us the advice to have a look at STL containers. We have googled and found some information, and "looking at it" works fine, however, working with it is somewhat "beyond" our C++ skills. If the "STL things" *are* our *only* solution, could some reader here provide us with a specific solution to exposing do_bar()? Or what else can we do to (1) use the class as is (because it works with dyn.load as well as in other software outside R) and (2) incorporate things into Rcpp modules (or other code) anyway?
>
> Thanks for all help!
>
> S?ren and Carlo
>
>
> On 07.05.2011, at 02:39, Dirk Eddelbuettel wrote:
>
>> S?ren and Carlo,
>>
>> On 6 May 2011 at 19:24, soeren.vogel at uzh.ch wrote:
>> | Hello
>> |
>> | We have a C++ class with several methods that manipulate an object. How is
>> | it possible to create several instances of that class *from R* in the C++
>> | realm, which can then be accessed via a given name character?
>>
>> Yes it is, and even somewhat easily given Rcpp modules as we tried to explain
>> over at the Rcpp-devel list when you asked there.  As a real quick
>> proof-of-concept, I did the following:
>>
>>
>> 1) Make sure you have a recent Rcpp such as 0.9.3 or 0.9.4
>>
>>
>> 2) Let Rcpp create a complete 'stub' of a working package with Rcpp modules
>>    support for you via the Rcpp.package.skeleton.function() with the
>>    module=TRUE argument:
>>
>>
>>    R>  library(Rcpp)
>>    R>  Rcpp.package.skeleton("simple", module=TRUE)
>>    Creating directories ...
>>    Creating DESCRIPTION ...
>>    Creating NAMESPACE ...
>>    Creating Read-and-delete-me ...
>>    Saving functions and data ...
>>    Making help files ...
>>    Done.
>>    Further steps are described in './simple/Read-and-delete-me'.
>>
>>    Adding Rcpp settings
>>>> added RcppModules: yada
>>>> added Depends: Rcpp
>>>> added LinkingTo: Rcpp
>>>> added useDynLib directive to NAMESPACE
>>>> added Makevars file with Rcpp settings
>>>> added Makevars.win file with Rcpp settings
>>>> added example header file using Rcpp classes
>>>> added example src file using Rcpp classes
>>>> added example R file calling the C++ example
>>>> added Rd file for rcpp_hello_world
>>>> copied the example module
>>    R>
>>
>>
>> 3) As you are keen to see that we get actual new objects, I am just doing
>>    the minimal code for by adding one for a new class member function:
>>
>>     void showmyaddress() const { std::cout<<  "Address is "<<  this<<  std::endl; }
>>
>>    which I add to the class 'World' in file simple/src/rcpp_module.rcpp -- on
>>    line 32 if it matters.   I also add this line to the module definition in
>>    the same file on line 62:
>>
>>      .const_method( "showmyaddress",&World::showmyaddress, "get *this ptr address")
>>
>>    It doesn't matter that the method is const, you can do without const in
>>    both eg
>>
>>     void showmyaddress() { std::cout<<  "Address is "<<  this<<  std::endl; }
>>
>>     .method( "showmyaddress",&World::showmyaddress, "get *this ptr address")
>>
>>    All that the code does is reveal its pointer to stdout.
>>
>>
>> 4) Install it via
>>
>>    $ R CMD INSTALL simple
>>
>>
>> 5) Try it in R (and I first
>>
>>    R>  library(simple)
>>    Loading required package: Rcpp
>>    R>  World
>>    C++ class 'World'<0x2b84940>
>>    Constructors:
>>        World()
>>
>>    Fields: No public fields exposed by this class
>>
>>    Methods:
>>         std::string greet()
>>               docstring : get the message
>>         void set(std::string)
>>               docstring : set the message
>>         void showmyaddress()  const
>>               docstring : get *this ptr address
>>    R>
>>    R>  w1<- new( World )
>>    R>  w1$showmyaddress()
>>    Address is 0x2748370
>>    R>
>>    R>  w2<- new( World )
>>    R>  w2$showmyaddress()
>>    Address is 0x2f960b0
>>    R>
>>
>>
>>    so w1 and w2 are indeed objects of class World which live in different
>>    memory locations.
>>
>> This should show the mechanics.  This is somewhat easy -- especially if you
>> know some C++ where it then helps you from having to write boiler plate code.
>> If you are relatively new to C and C++, it can be a little tougher.  Either
>> way, to my mind it is shorter (and I'd argue, easier) than anything you could
>> do in plain C with the standard R API.
>>
>> Good luck, and please bring Rcpp questions to rcpp-devel.
>>
>> Regards, Dirk
>>
>>
>>
>> | Symbolic example (we hope this illustrates our problem):
>> |
>> | // C++ side:
>> | class Foo{
>> | ...
>> | }
>> | // perhaps:
>> | void my_new_instance_wrapper("the_character") // plain to see that I am no C++ programmer ;-)
>> | {
>> |   static Foo "the_character"; // no return needed since we know the name of the instance = "the_character"
>> | }
>> |
>> | # R side:
>> | create_new_instance<- function(name){
>> |   dono_what_to_use_here(???, class)
>> | }
>> | # perhaps:
>> | create_new_instance<- function(name){
>> |   .C("my_new_instance_wrapper", as.character(name))
>> | }
>> |
>> | dyn.load("Foo")
>> | obj1<- create_new_instance("bar", class="Foo")
>> | obj2<- create_new_instance("baz", class="Foo")
>> | str(obj1)
>> | : character which can be manipulated using class methods in the C++ realm
>> |
>> | What we do not want: make simple copies of the object in R; use Rcpp modules (we tried that without success, pointers in constructors cause trouble); re-write our code such that C++ only "works off" heavy code, the rest is R-side. What we want: interfacing (from the R-side) instances of our class where the instances exist in the C++ realm.
>> |
>> | Either there is a function (or code) in R that solve this task, perhaps by returning pointers to instances of C++ classes. (Or there is a possibility to create a wrapper in C++ creating a new instance, the wrapper we do not know of.)
>> |
>> | Thanks for any notes, tips, experiences.
>> |
>> | S?ren and Carlo
>
>
>
> R: sessionInfo()
>
> R version 2.13.0 (2011-04-13)
> Platform: i386-apple-darwin9.8.0/i386 (32-bit)
>
> locale:
> [1] en_US.UTF-8/en_US.UTF-8/C/C/en_US.UTF-8/en_US.UTF-8
>
> attached base packages:
> [1] stats     graphics  grDevices utils     datasets  methods   base
>
> other attached packages:
> [1] Rcpp_0.9.4
>
> loaded via a namespace (and not attached):
> [1] tools_2.13.0
>
>
>
> /* ### Foo_mod.cpp ### */
> #include<Rcpp.h>
>
> class Foo
> {
> 	int N, M, n, m;
> 	double dtau;
> 	double * C;
> 	double * t;
> 	double * s;
> 	double * par;
> 	double * D;
> 	double * ee;
> 	double * ff;
> 	double * S;
> 	int * y;
> 	public:
> 		Foo(int N_, int M_, int n_) : N(N_), M(M_), n(n_)
> 		{
> 			D = new double[M];
> 			ee= new double[N];
> 			ff= new double[N];
> 			S = new double[n+1];
> 		}
> 		~Foo()
> 		{
> 			delete[] D;
> 			delete[] ee;
> 			delete[] ff;
> 			delete[] S;
> 		}
> 		// important methods
> //		void set_experiment(int m, double *C, double *s); // original code
> 		void do_foo(int m);
> 		void do_bar(double *C);
> 		// other stuff
> 		void set_data(int n, int *y, double *t);
> 		void set_accuracy(int N, int M);
> 		void set_par(double *par);
> 		double loglikelihood(double *z);
> };
>
> //void Foo::set_experiment(int mm, double *CC, double *ss)
> void Foo::do_foo(int mm)
> {
> 	m=mm;
> }
> void Foo::do_bar(double *CC)
> {
> 	C=CC;
> }
>
> RCPP_MODULE(mod_foo)
> {
> 	using namespace Rcpp;
> 	class_<Foo>( "Foo" )
> 		.constructor<int,int,int>()
> 		.method("do_foo",&Foo::do_foo) // works
> 		.method("do_bar",&Foo::do_bar) // does not work!
> 	;
> }
>
>
> ### compile warning with the working version:
> ** checking whether the name space can be loaded with stated dependencies ... WARNING
> Error: .onLoad failed in loadNamespace() for 'Foo', details:
>    call: value[[3L]](cond)
>    error: failed to load module mod_foo from package Foo
> Execution halted
> A namespace must be able to be loaded with just the base namespace
> loaded: otherwise if the namespace gets loaded by a saved object, the
> session will be unable to start.
> Probably some imports need to be declared in the NAMESPACE file.
>
>
> ### 00install.out
> * installing *source* package ?Foo? ...
> ** libs
> *** arch - i386
> g++-4.2 -arch i386 -I/Library/Frameworks/R.framework/Resources/include -I/Library/Frameworks/R.framework/Resources/include/i386  -I/usr/local/include -I"/Library/Frameworks/R.framework/Versions/2.13/Resources/library/Rcpp/include"   -fPIC  -g -O2 -c Foo_mod.cpp -o Foo_mod.o
> /Library/Frameworks/R.framework/Versions/2.13/Resources/library/Rcpp/include/Rcpp/traits/Exporter.h: In constructor ?Rcpp::traits::Exporter<T>::Exporter(SEXPREC*) [with T = double*]?:
> /Library/Frameworks/R.framework/Versions/2.13/Resources/library/Rcpp/include/Rcpp/as.h:51:   instantiated from ?T Rcpp::internal::as(SEXPREC*, Rcpp::traits::r_type_generic_tag) [with T = double*]?
> /Library/Frameworks/R.framework/Versions/2.13/Resources/library/Rcpp/include/Rcpp/as.h:75:   instantiated from ?T Rcpp::as(SEXPREC*) [with T = double*]?
> /Library/Frameworks/R.framework/Versions/2.13/Resources/library/Rcpp/include/Rcpp/module/Module_generated_CppMethod.h:122:   instantiated from ?SEXPREC* Rcpp::CppMethod1<Class, void, U0>::operator()(Class*, SEXPREC**) [with Class = Foo, U0 = double*]?
> Foo_mod.cpp:59:   instantiated from here
> /Library/Frameworks/R.framework/Versions/2.13/Resources/library/Rcpp/include/Rcpp/traits/Exporter.h:31: error: cannot convert ?SEXPREC*? to ?double*? in initialization
> make: *** [Foo_mod.o] Error 1
> ERROR: compilation failed for package ?Foo?
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>
>


-- 
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



[Rd] Create and access several instances of a C++ class from R
Romain Francois