将用户创建的c ++函数作为参数传递给rcpp

dle*_*eal 3 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
Run Code Online (Sandbox Code Playgroud)

我尝试过x = XPtr<funcPtr>fun2(theta,gamma)但没有给出理想的结果.

nru*_*ell 7

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

*/
Run Code Online (Sandbox Code Playgroud)

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

  • 一个......唯一...... @nrussell女士们,先生们! (3认同)