convert Rcpp::CharacterVector to std::string

妖精的绣舞 提交于 2019-11-29 02:36:47

问题


I am trying to open a file within an Rcpp function, so I need the file name as a char* or std::string.

So far, I have tried the following:

#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;
}

But apparently, as does not work for Rcpp::CharacterVector as I get a compile time error.

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

Is there a simple way to get a string from the argument or somehow open a file from the Rcpp function argument?


回答1:


Rcpp::as() expects a SEXP as input, not a Rcpp::CharacterVector. Try passing the f1 parameter directly to Rcpp::as(), eg:

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

Or:

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



回答2:


The real issue is that Rcpp::as requires that you specify the type you want to convert to manually, such as Rcpp::as<std::string>.

The input of all as overloads is always a SEXP so the compiler does not know which one to use and cannot make the decision automatically. that's why you need to help it. Things work differently for wrap which can use the input type to decide which overload it will use.



来源:https://stackoverflow.com/questions/8421250/convert-rcppcharactervector-to-stdstring

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!