【问题标题】:Passing class as argument in Rcpp function在 Rcpp 函数中将类作为参数传递
【发布时间】:2021-02-10 18:00:11
【问题描述】:

我正在阅读很棒的 Rcpp vignette 关于使用 Rcpp 模块公开 c++ 类和函数的内容。在这种情况下,是否可以创建一个 Rcpp 函数,该函数将 Uniform 类型的类作为参数之一,并且不属于要导出的特定模块的一部分?下面只是我所想的一个模型。该示例取自同一插图。答案可能已经存在。如果有人能指出正确的地方,那就太好了。

#include <RcppArmadillo.h>
using namespace Rcpp;

class Uniform {

public:
  Uniform(double min_, double max_) :
  min(min_), max(max_) {}
  
  NumericVector draw(int n) const {
    RNGScope scope;
    return runif(n, min, max);
  }
  
  double min, max;
};


double uniformRange(Uniform* w) {
  return w->max - w->min;
}


RCPP_MODULE(unif_module) {
  
  class_<Uniform>("Uniform")
  
  .constructor<double,double>()
  .field("min", &Uniform::min)
  .field("max", &Uniform::max)
  
  .method("draw", &Uniform::draw)
  .method("range", &uniformRange)
  ;
}

/// JUST AN EXAMPLE: WON'T RUN
// [[Rcpp::export]]
double test(double z, Uniform* w) {
  return z + w->max ;
}

【问题讨论】:

  • 可能相关:我刚刚在 GH 问题单中写/清理过的东西在这里。您可以清楚地传递 XPtr 对象。 github.com/RcppCore/Rcpp/issues/1140#issuecomment-776359009 让我知道是否有帮助...
  • @DirkEddelbuettel,我正在查看您的答案。谢谢!我认为它回答了这个问题。我将在几分钟后在此处发布解决方案,您可以进行编辑。有一个与您的帖子有关的问题。既然有一个类的新实例,上面有一个指针,是否需要删除?
  • 非常周到 :) -- XPtr 构造函数的第二个参数通常设置它。 (它通常有效,我在一个应用程序中发现我需要仔细检查,所以我想回到这个问题,请参阅 Rcpp 存储库中的问题 #1108。)
  • 我明白了。在这方面,您能否指出该 ptr() 命令的良好文档?实际上,我必须处理包含大型 arma 矩阵、字段和向量的多个类,所以我只需要非常小心!
  • 我建议你来rcpp-devel列表,举个小例子?这 200 个字符集适合真正的对话。

标签: rcpp


【解决方案1】:

根据 Dirk 的评论,我发布了一个可能的解决方案。这个想法是创建一个带有指针的类对象的新实例,并创建一个可以进一步作为函数参数传递的外部指针。下面是我从他的post收集到的内容:

#include <RcppArmadillo.h>
using namespace Rcpp;

class Uniform {

public:
  Uniform(double min_, double max_) :
  min(min_), max(max_) {}
  
  NumericVector draw(int n) const {
    RNGScope scope;
    return runif(n, min, max);
  }
  
  double min, max;
};

// create external pointer to a Uniform object
// [[Rcpp::export]]
XPtr<Uniform> getUniform(double min, double max) {
  // create pointer to an Uniform object and
  // wrap it as an external pointer
  Rcpp::XPtr<Uniform> ptr(new Uniform( min, max ), true);
  // return the external pointer to the R side
  return ptr;
}

/// CAN RUN IT NOW: 
// [[Rcpp::export]]
double test(double z, XPtr<Uniform> xp) {
  
  double k = z + xp ->max;
  
  return k;
  
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 2018-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多