代码之家  ›  专栏  ›  技术社区  ›  George

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

  •  0
  • George  · 技术社区  · 6 年前

    我试图用一个函数作为另一个函数的参数。

    我正在做一个包裹。

    功能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 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
    

    但我还是会犯同样的错误。

    1 回复  |  直到 6 年前
        1
  •  3
  •   Ralf Stubner    6 年前

    问题是你的 typedef 未导出到 RcppExports.cpp . 参见第节 2.4.生成代码中的类型 Rcpp attribute vignette .简而言之:将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 .