[Rcpp-devel] Create an instance of a reference class for a C++ class exported as a module from within C++?

Romain Francois romain at r-enthusiasts.com
Tue Jun 7 15:42:48 CEST 2011

Le 02/06/11 22:31, Douglas Bates a écrit :
> Sorry for the long subject line but I hope it describes what I want to
> do.  I have a C++ class, dgTMatrix, that is exported in a module
> definition.
> ...
>      class_<dgCMatrix>("dgCMatrix")
>      ...
>      ;
> }
> Many of the methods for this class return other members of this class.
>   Can I create a new instance of the reference class in R from within
> the module?  I'm sure it is possible, I'm just wondering if there is
> an easy way to do this without duplicating large chunks of the code in
> Rcpp/src/Module.cpp.  Can i somehow clone the SEXP representing the
> current instance then swap the external pointer to the C++ object?

As part of the changes I've made today [see the post "returning pointers 
in module methods" ], there is this function you might be interested in 
(in Module.h):

namespace internal {
template <typename Class>
SEXP make_new_object( Class* ptr ){
     Rcpp::XPtr<Class> xp( ptr, true ) ;
	Function maker = Environment::Rcpp_namespace()[ "cpp_object_maker"] ;
	return maker( typeid(Class).name() , xp ) ;

Maybe I should make it more public (i.e not have it in internal).

Anyway, if you give this function a pointer to an instance of a class 
that has been exposed through modules, it will create the associated R 
ref class object.


Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
|- http://bit.ly/kaSV6U : Stand up set at Up The Creek
|- http://bit.ly/hdKhCy : Rcpp article in JSS
`- http://bit.ly/elZJRJ : Montpellier Comedie Club - Avril 2011

More information about the Rcpp-devel mailing list