[Rcpp-devel] Create an instance of a reference class for a C++ class exported as a module from within C++?
Christian Gunning
xian at unm.edu
Mon Jun 6 06:09:05 CEST 2011
> At the moment the only way i see is to make an R call to "new" and construct the object this way...
>> 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?
I played with this a little more, and the following works fine.
Nothing striking here. The part I don't understand is, can you employ
the SEXP returned by spawn() as an instance of Bar, or are you then
stuck with the R interface to Bar?
-Christian
## in R
Rcpp.package.skeleton('testmod', module=T)
//in testmod/src/rcpp_module.cpp
#include <Rcpp.h>
using namespace Rcpp;
class Bar {
public:
Bar() {}
void set(int state_) { this->state = state_; }
int get() { return state; }
SEXP spawn() {
Environment meth("package:methods");
Function Rnew = meth["new"];
Function Rget("get");
SEXP NewObj( Rnew(Rget("Bar")) );
return NewObj;
}
private:
int state;
};
## in R
require(testmod)
bb = new(Bar); bb$set(3)
cc = bb$spawn(); cc$set(4)
bb$get(); cc$get()
--
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
More information about the Rcpp-devel
mailing list