[Rcpp-devel] convert std::string to Rcpp::RawVector

Romain Francois romain at r-enthusiasts.com
Fri Oct 8 15:03:27 CEST 2010


Le 07/10/10 22:04, Koert Kuipers a écrit :
> Hello all,
> I need to convert a std::string to a RAWSXP. I think i know hot do to this
> without Rcpp. It goes something like this (i haven't tested this):
>
> SEXP stringToRaw(std::string x) {
> SEXP y;
> PROTECT(y = allocVector(RAWSXP, x.length()));
> memcpy(RAW(y), x.data(), x.length());
> UNPROTECT(1);
> return y;
> }
>
> How do i do this with Rcpp? Say i want to return a Rcpp::RawVector?
> Thanks,
> Koert

Hi,

I would litteraly C++ify the code you have to make something like this:


require( inline )
require( Rcpp )

fx <- cxxfunction( , '

     std::string foo( "blabla" ) ;
     RawVector res( foo.size() ) ;
     std::copy( foo.begin(), foo.end(), res.begin() ) ;
     return res ;

', plugin = "Rcpp" )


 > fx( )
[1] 62 6c 61 62 6c 61

 > charToRaw( "blabla" )
[1] 62 6c 61 62 6c 61

Romain

-- 
Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
http://romainfrancois.blog.free.fr
|- http://bit.ly/b8wOqW : LondonR Rcpp slides
|- http://bit.ly/cCmbgg : Rcpp 0.8.6
`- http://bit.ly/bzoWrs : Rcpp svn revision 2000




More information about the Rcpp-devel mailing list