c++ - 将 Rcpp::CharacterVector 转换为 std::string

标签 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;
}

但显然,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

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

最佳答案

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

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

或者:

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

关于c++ - 将 Rcpp::CharacterVector 转换为 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8421250/

相关文章:

r - 是否可以在 R 包之间共享 C++ 类?

c++ - 映射插入键但不插入值

c++,无符号字符之间的线性插值

c++ - 根据 move 赋值运算符 move 构造函数

string - 在可以出现零次或多次的字符后截断R中字符串的结尾

r - 使用测地线或大圆距离在 R 中进行空间测地纬度经度聚类的方法

c++ - 如何使用std算法来替换这个for循环?

使用 fread、data.table 包读取链 (+, -) 列

Rcpp::DataFrame::create 仅限于 20 个参数?

c++ - 通过 Rcpp 和 bit64 R 包将最大的 int64_t 变量值从 C++ 传递到 R