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

C++ 将Rcpp::CharacterVector转换为std::string,c++,r,rcpp,C++,R,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);

我试图在函数中打开一个文件,因此需要文件名为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;
}
有没有一种简单的方法可以从参数中获取字符串或以某种方式从Rcpp函数参数中打开文件?

Rcpp::as()
需要一个
SEXP
作为输入,而不是
Rcpp::CharacterVector
。尝试将
f1
参数直接传递到
Rcpp::as()
,例如:

std::string fname = Rcpp::as(f1); 
或:

std::string fname=Rcpp::as(f1);

真正的问题是
Rcpp::as
要求您指定要手动转换为的类型,例如
Rcpp::as


所有
as
重载的输入总是一个
SEXP
,因此编译器不知道使用哪一个,无法自动做出决定。这就是为什么你需要帮助它。对于
wrap
,情况有所不同,它可以使用输入类型来决定将使用哪个重载

Rcpp::as(ff)有效吗?@IanFellows,是的,有效
Rcpp::as
可与
SEXP
Rcpp::CharacterVector
std::string fname = Rcpp::as(f1); 
std::string fname = Rcpp::as<std::string>(f1);