抱歉,如果这是一个愚蠢的问题,因为我不是c++或Rcpp专家,但可以从R访问c++数据成员吗?我下面的尝试失败了:
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发布于 2017-12-09 00:43:14
我会用
#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();
}https://stackoverflow.com/questions/47717325
复制相似问题