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

function was not declared (function as argument to another)- XPtr when creating package

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

我正在构建一个包。

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(&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 scope template argument 1 is invalid template argument 3 is invalid invalid 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 attribute vignette 的 Generated Code 中键入。简而言之:将 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.