gpt4 book ai didi

c++ - 从 R 访问 C++ 对象数据成员

转载 作者:搜寻专家 更新时间:2023-10-31 02:08:18 25 4
gpt4 key购买 nike

如果这是一个愚蠢的问题,我深表歉意,因为我不是 C++ 或 Rcpp 专家,但是否可以从 R 访问 C++ 数据成员?我的以下尝试失败了:

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

测试.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++ - 从 R 访问 C++ 对象数据成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47717325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com