代码之家  ›  专栏  ›  技术社区  ›  F. Privé

在RCPP中获取全局选项

  •  0
  • F. Privé  · 技术社区  · 7 年前

    我想得到一个选项的值(例如 "width" )在RCPP内部。我试过:

    #include <Rcpp.h>
    using namespace Rcpp;
    
    // [[Rcpp::export]]
    int test_option() {
    
      Environment base("package:base");
      Function get_option = base["getOption"];
      return get_option("width");
    }
    
    // [[Rcpp::export]]
    int test_option2() {
    
      Environment base("package:base");
      Function get_option = base["options"];
      List l_width = get_option("width");
      return l_width[1];
    }
    

    第一个函数不编译,第二个函数崩溃会话。

    知道怎么做吗?

    2 回复  |  直到 7 年前
        1
  •  8
  •   coatless    7 年前

    代码不能工作的原因是太依赖rcpp的automagic转换 是的。您需要创建一个中间步骤。 召回 那个 没有标量的概念 int 数据类型。

    让我们看看使用rinternal宏返回的类型 Rf_type2char(TYPEOF(x))

    到岸价

    #include<Rcpp.h>
    
    // [[Rcpp::export]]
    void test_option() {
    
      Rcpp::Environment base("package:base");
      Rcpp::Function get_option = base["getOption"];
      Rcpp::Rcout << Rf_type2char(TYPEOF(get_option("width")));
    }
    

    这就提供了:

    test_option()
    # integer
    

    从这里开始,添加返回类型:

    #include<Rcpp.h>
    
    // [[Rcpp::export]]
    Rcpp::IntegerVector  get_width() {
    
      Rcpp::Environment base("package:base");
      Rcpp::Function get_option = base["getOption"];
      Rcpp::IntegerVector out = get_option("width");
    
      return out;
    }
    

    输出:

    get_width()
    # [1] 155
    
        2
  •  2
  •   G. Grothendieck    7 年前

    测试选项

    如果你这样写,你的第一个函数就会工作:

    SEXP test_option() {
    

    或者这个:

    IntgerVector test_option() {
    

    测试选项2

    关于你问题中的第二个函数,你在评论中写到你的目标是把sexp转换成 int 所以在这种情况下,如果 s 是一个 SEXP 然后保持整数 as<int>(s) INTEGER(s)[0] 是一个 内景 是的。这与 IntegerVector 是的。如果你真的想写你想要的 积分仪 然后分别替换 内景 下面是 积分仪 是的。

    将下面的代码放在当前目录下的myoption.cpp中,并按照第一行中的说明进行操作。

    // To run: library(Rcpp); sourceCpp("myOption.cpp")
    
    #include <Rcpp.h>
    using namespace Rcpp;
    
    // [[Rcpp::export]]
    int myOption(CharacterVector x) {
      Environment base( "package:base" ) ;
      Function getOption = base["getOption"];
      SEXP s = getOption(x);
      int i = as<int>(s);
      return i;
    }
    
    /*** R
    myOption("width")
    */