Я пытаюсь использовать функцию в качестве аргумента для другой функции.
Я создаю пакет.
func1.cpp:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector timesTwo(NumericVector x) {
return x * 2;
}
main.cpp:
#include <Rcpp.h>
#include <cmath>
#include <cstdio>
#include <cstdlib>
// [[Rcpp::plugins(cpp11)]]
using namespace Rcpp;
NumericVector timesTwo(NumericVector x);
typedef NumericVector (*timesTwo_call)(NumericVector x);
// [[Rcpp::export]]
XPtr<timesTwo_call> putFunPtrInXPtr(std::string fstr) {
if (fstr == "timesTwo")
return(XPtr<timesTwo_call>(new timesTwo_call(×Two)));
else
return XPtr<timesTwo_call>(R_NilValue); // runtime error as NULL no XPtr
}
// [[Rcpp::export]]
NumericVector testFunc(SEXP func, NumericVector x)
{
XPtr<timesTwo_call> xpfun(func);
timesTwo_call fun = *xpfun;
NumericVector tmp = fun(x);
const int N = tmp.size();
NumericVector result(N);
for (int i = 0; i < N; ++i)
{
result[i] = tmp[i] * 3;
}
return result;
}
/*** R
x <- c(1,2,3)
fun <- putFunPtrInXPtr("timesTwo")
result <- testFunc(fun, x)
*/
Попытка сборки дает мне несколько ошибок в RcppExports.cpp, в строке:
XPtr<timesTwo_call> putFunPtrInXPtr(std::string fstr);
Ошибки:
timesTwo_call was not declared in this scope
template argument 1 is invalid
template argument 3 is invalid
invalid type in declaration before ' token
- ОБНОВЛЕНИЕ -
Следует отметить, что даже если я добавлю определение timesTwo
в основной файл, явсе равно получаются те же ошибки.
Но, если (когда я поместил определение в main) запустить как sourceCpp, то это работает!
- UPDATE 2 ---
Я создал файл test_types.h
в папке src (где находятся все файлы cpp).
#ifndef TEST_TYPES_H
#define TEST_TYPES_H
#include <Rcpp.h>
using namespace Rcpp;
typedef NumericVector (*timesTwo_call)(NumericVector x);
NumericVector timesTwo(NumericVector x);
#endif
, но все равно получаю те же ошибки.