我试图用一个函数作为另一个函数的参数。
我正在做一个包裹。
功能1.cpp:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector timesTwo(NumericVector x) {
return x * 2;
}
主.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运行,那么它就可以工作了!
--更新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
但我还是会犯同样的错误。