2017-04-25 2 views
0

이것은 기본적인 질문 일 수 있습니다. 사용자 생성 cC++ 함수를 Rcpp에 전달하는 데 어려움을 겪고 있습니다. 설명서를 읽었을 때 XPtr (Link : http://gallery.rcpp.org/articles/passing-cpp-function-pointers/)에서 제공하는 SEXP 줄 바꿈을 사용해야하는 것 같습니다. 그러나이 작업을 올바르게 수행하는 방법은 아직 명확하지 않습니다. 다음에서는 C++ 방식의 testfun에서 인수로 funcPtrG 함수를 사용하려고합니다. 나는 다음과 같은 오류가 발생합니다 :rcpp에 사용자 생성 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) 퍼팅을 시도했지만 원하는 결과를 제공하지 않았다.

+0

나는 그렇다! 실례합니다. 편집을하겠습니다. 내 원래 프로그램에서 모든 함수 앞에 // [[Rcpp :: export]]가 붙어 있습니다. – dleal

답변

5

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 함수는 인스턴스를 R 측면에 작성하는 방법을 제공하며,이 인수는 함수 인수를 통해 C++로 다시 전달 될 수 있습니다.

+0

이것은 제 목적을 위해 잘 작동합니다. 고마워요 – dleal

+2

그 중 하나 ... 유일한 ... @ nrussell 신사 숙녀 여러분! – coatless