将Rcpp :: CharacterVector转换为std :: string

hig*_*dth 21 c++ r rcpp

我试图在Rcpp函数中打开一个文件,所以我需要文件名作为char*或std :: string.

到目前为止,我尝试过以下方法:

#include <Rcpp.h>
#include <boost/algorithm/string.hpp>
#include <fstream>
#include <string>

RcppExport SEXP readData(SEXP f1) {
    Rcpp::CharacterVector ff(f1);
    std::string fname = Rcpp::as(ff);
    std::ifstream fi;
    fi.open(fname.c_str(),std::ios::in);
    std::string line;
    fi >> line;
    Rcpp::CharacterVector rline = Rcpp::wrap(line);
    return rline;
}
Run Code Online (Sandbox Code Playgroud)

但显然,因为我得到编译时错误as不起作用Rcpp::CharacterVector.

foo.cpp: In function 'SEXPREC* readData(SEXPREC*)':
foo.cpp:8: error: no matching function for call to 'as(Rcpp::CharacterVector&)'
make: *** [foo.o] Error 1
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法从参数中获取字符串或以某种方式从Rcpp函数参数中打开文件?

Rem*_*eau 24

Rcpp::as()期望SEXP输入,而不是Rcpp::CharacterVector.尝试f1直接将参数传递给Rcpp::as(),例如:

std::string fname = Rcpp::as(f1); 
Run Code Online (Sandbox Code Playgroud)

要么:

std::string fname = Rcpp::as<std::string>(f1); 
Run Code Online (Sandbox Code Playgroud)

  • `Rcpp :: as <std :: string>`适用于`SEXP`和`Rcpp :: CharacterVector` (2认同)

Rom*_*ois 16

真正的问题是Rcpp::as需要您手动指定要转换的类型,例如Rcpp::as<std::string>.

所有as重载的输入总是SEXP如此,因此编译器不知道使用哪一个并且不能自动做出决定.这就是你需要帮助它的原因.事情的工作方式不同wrap,可以使用输入类型来决定它将使用哪个重载.