从 R 访问 C++ 对象数据成员
Accessing c++ object data members from R
如果这是一个愚蠢的问题,我深表歉意,因为我不是 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
我会用
#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();
}
如果这是一个愚蠢的问题,我深表歉意,因为我不是 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
我会用
#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();
}