Reputation: 327
Apologies if this is a silly question as I am not a c++ or Rcpp expert but is it possible to access c++ data members from R? My attempt below fails:
test.cpp
#include <Rcpp.h>
using namespace Rcpp;
class myclass {
private:
int k;
public:
myclass(int &n) : k(n){}
int getk() const {return k;}
};
typedef myclass* pmyclass;
// [[Rcpp::export]]
XPtr<pmyclass> new_myclass(NumericVector n_) {
int n = as<int>(n_);
myclass x(n);
return(XPtr<pmyclass>(new pmyclass(&x)));
}
// [[Rcpp::export]]
NumericVector getk(SEXP xpsexp){
XPtr<pmyclass> xp(xpsexp);
pmyclass x = *xp;
return wrap(x -> getk());
}
test.R
library(Rcpp)
sourceCpp('./cpp_attempt/live_in_cpp/minimal_fail/test.cpp')
ptr <- new_myclass(10)
getk(ptr)
#19274768
Upvotes: 2
Views: 267
Reputation: 11728
I would use
#include <Rcpp.h>
using namespace Rcpp;
class myclass {
private:
int k;
public:
myclass(int n) : k(n){}
int getk() const {return k;}
};
// [[Rcpp::export]]
SEXP new_myclass(int n) {
XPtr<myclass> ptr(new myclass(n), true);
return ptr;
}
// [[Rcpp::export]]
int getk(SEXP xpsexp){
XPtr<myclass> xp(xpsexp);
return xp->getk();
}
Upvotes: 2