从R中访问C 对象数据成员

Accessing c++ object data members from R

本文关键字:对象 数据成员 访问      更新时间:2023-10-16

是否是一个愚蠢的问题,因为我不是C 或RCPP专家,但是是否可以从R访问R?我下面的尝试失败:

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();
}