r - 将用户在 rcpp 中创建的 C++ 函数作为参数传递

标签 r rcpp

这可能是一个基本问题,我一直在努力在 Rcpp 中传递用户创建的 C++ 函数。我阅读了文档,似乎我应该使用 XPtr 提供的 SEXP 包装(链接: http://gallery.rcpp.org/articles/passing-cpp-function-pointers/ )但是,我仍然不太清楚如何正确执行此操作。接下来,我想使用一个函数 funcPtrG 作为 testfun 中的参数,C++ 方式。我收到如下错误:

     #include <RcppArmadillo.h>
        typedef double (*funcPtrG)(double theta, double gamma);
        using namespace Rcpp;

    // [[Rcpp::export]]
    double GGfuncpp(double theta, double gamma){
      double new_gamma = 0;
      new_gamma = theta*gamma + R::rnorm(0,1)*0.0001;
      return new_gamma;
    }
    // [[Rcpp::export]]
    double testfun(funcPtrG fun2, double theta, double gamma){
      double x= 0;
      x = fun2(theta,gamma);
      return x;
    }

    Error: cannot convert 'SEXP' to 'double (*)(double, double)' in initialization

我尝试输入 x = XPtr<funcPtr>fun2(theta,gamma)但没有给出想要的结果。

最佳答案

IIUC,您正在寻找这样的东西:

#include <Rcpp.h>
using namespace Rcpp;

typedef double (*funcPtrG)(double theta, double gamma);
typedef XPtr<funcPtrG> fptr_t;

// [[Rcpp::export]]
double GGfuncpp(double theta, double gamma)
{
    Rcout << "GGfuncpp called\n";
    double new_gamma = 0;
    new_gamma = theta*gamma + R::rnorm(0, 1) * 0.0001;
    return new_gamma;
}

// [[Rcpp::export]]
double GGfuncpp2(double theta, double gamma)
{
    Rcout << "GGfuncpp2 called\n";
    return 1.0;
}

// [[Rcpp::export]]
fptr_t make_GGfuncpp()
{
    return fptr_t(new funcPtrG(GGfuncpp));
}

// [[Rcpp::export]]
fptr_t make_GGfuncpp2()
{
    return fptr_t(new funcPtrG(GGfuncpp2));
}

// [[Rcpp::export]]
double testfun(fptr_t fun2, double theta, double gamma)
{
    double x= 0;
    x = (*fun2)(theta, gamma);
    return x;
}

/*** R

fptr1 <- make_GGfuncpp()
fptr2 <- make_GGfuncpp2()

testfun(fptr1, 1, 5)
# GGfuncpp called
# [1] 5.000084

testfun(fptr2, 1, 5)
# GGfuncpp2 called
# [1] 1

*/
<小时/>

R 没有任何 funcPtrG 的概念,因此不能直接将其作为函数参数类型传递。相反,这些对象需要包装在 XPtr 中模板。 make_GGfuncppmake_GGfuncpp2函数提供了一种创建 XPtr<funcPtrG> 的方法R 端的实例,然后可以通过函数参数传递回 C++。

关于r - 将用户在 rcpp 中创建的 C++ 函数作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43616778/

相关文章:

r - 如何提取具有最小值或最大值的行?

R 指定时间戳差异的单位

在所有 NA 的情况下,R 将行总和返回为零

regex - 删除字符串中最后一个句点后的初始句点和文本

c++ - 对工作程序中自定义函数的 undefined reference (C++ 和 RcppParallel)

r - 优化 R 中大数据文件的循环,可能使用 Rcpp

r - 如何根据单元格中的字符值对 gt 表中的单元格进行着色?

c++ - 将 Rcpp::NumericVector 转换为 Eigen::VectorXd

eclipse - 如何在 Windows 上设置 Eclipse + StatET + Rcpp

Rcpp 链接到外部库 (NLopt)