Last active
March 19, 2020 01:38
-
-
Save slwu89/0832253bbead940a9d4d900dda3c318d to your computer and use it in GitHub Desktop.
for when you want to return a std::function to R wrapped in a struct to be evaluated later
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <functional> | |
#include <Rcpp.h> | |
// [[Rcpp::plugins(cpp14)]] | |
using my_lambda = std::function<double(const double)>; | |
typedef struct lambda_st { | |
my_lambda func; | |
lambda_st(){Rcpp::Rcout << "lambda_st ctor called at " << this << "\n";} | |
~lambda_st(){Rcpp::Rcout << "lambda_st dtor called at " << this << "\n";} | |
} lambda_st; | |
// make a silly lambda | |
my_lambda make_my_lambda(const double x0){ | |
my_lambda lambda = [x0=x0](const double x1) -> double { | |
return x0 + x1; | |
}; | |
return lambda; | |
} | |
// the R interface | |
// [[Rcpp::export]] | |
Rcpp::XPtr<lambda_st> make_my_lambdaR(const double x0){ | |
lambda_st* lambdastruct = new lambda_st; | |
lambdastruct->func = make_my_lambda(x0); | |
Rcpp::XPtr<lambda_st> xptr(lambdastruct); | |
return xptr; | |
} | |
// [[Rcpp::export]] | |
double evaluate_my_lambdaR(SEXP xptr, const double x1){ | |
Rcpp::XPtr<lambda_st> lambda_st_xptr(xptr); | |
double out = lambda_st_xptr->func(x1); | |
return out; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment