r语言 - 函数未声明(函数作为另一个参数)- 创建包时 XPtr



我正在尝试使用一个函数作为另一个函数的参数。

我正在构建一个包。

函数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(&timesTwo)));
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 scopetemplate argument 1 is invalidtemplate argument 3 is invalidinvalid type in declaration before ' token

--更新--

我应该注意,即使我将timesTwo的定义放在主文件中,我仍然会收到相同的错误。

但是,如果(当我将定义放在 main 中时(作为 sourceCpp 运行,那么它可以工作!

-- 更新 2 ---

我在src文件夹(所有cpp文件所在的位置(下创建了文件test_types.h

#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

但我仍然收到同样的错误。

问题是您的typedef没有导出到RcppExports.cpp. 请参阅第2.4 节。在生成的代码中键入rcpp 属性晕影。简而言之:将 typedef 放入名为:

src/<pkg>_types.h
src/<pkg>_types.hpp
inst/include/<pkg>_types.h
inst/include/<pkg>_types.hpp
inst/include/<pkg>.h

此文件将自动包含在RcppExports.cpp中。您必须手动将其包含在main.cpp.

最新更新