Using Rcpp, how to convert RawVector back/forth to a string?

Viewed 39

There is a discussion on Rccp-dev discussing how to convert from a string result to a RawVector (see https://lists.r-forge.r-project.org/pipermail/rcpp-devel/2010-October/001179.html).

// [[Rcpp::export]]
RawVector say_hello()
{
    std::string res = "hello friend";
    RawVector raw( res.size() ) ;
    std::copy( res.begin(), res.end(), raw.begin() ) ;
    return raw ;
}

It works as expected:

> Rcpp::sourceCpp( paste0(wd, "src/base64.cpp") );
> say_hello()
 [1] 68 65 6c 6c 6f 20 66 72 69 65 6e 64
> charToRaw("hello friend")
 [1] 68 65 6c 6c 6f 20 66 72 69 65 6e 64

Question: How to go the other direction in Rcpp?

If I have a RawVector how to transform it to a std::string? That is the equivalent of the rawToChar function within Rcpp?

> rawToChar ( charToRaw("hello friend") )
[1] "hello friend"

Clarification

Analogous to the above code with rawToChar and charToRaw, I want to have the following: print_hello(say_hello()) which should output "hello friend".

That is, I am trying to pass in a raw vector from R and have it convert the raw format to a std:string:

ONE FAILED attempt

// [[Rcpp::export]]
std::string print_hello(const RawVector& raw)
{   
    // https://stackoverflow.com/questions/8421250/convert-rcppcharactervector-to-stdstring
    std::string res = Rcpp::as<std::string>(raw);
    return res ;
}

ANOTHER FAILED ATTEMPT (THIS IS THE FORMAT I AM LOOKING FOR)

Here I included the Rccp serialize API: #include "RApiSerializeAPI.h"

#include "RApiSerializeAPI.h
std::string print_hello(const RawVector raw)
{   
    // https://github.com/eddelbuettel/rcppredis/blob/master/src/Redis.cpp
    std::string res = unserializeFromRaw(raw);
    return res ;
}

The errors are always similar:

base64.cpp:155:38: error: conversion from 'SEXP' {aka 'SEXPREC*'} to non-scalar type 'std::string' {aka 'std::__cxx11::basic_string<char>'} requested
  155 |  std::string res = unserializeFromRaw(raw);
  

A final try, also fails

std::string print_hello(SEXP s)
{   
    // https://github.com/eddelbuettel/rcppredis/blob/master/src/Redis.cpp
    Rcpp::RawVector raw = (TYPEOF(s) == RAWSXP) ? s : serializeToRaw(s);
    std::string res = unserializeFromRaw(raw);
    return res ;
}

There is a reference to a static_cast that I don't understand as well. The goal is: convert a RawVector to a std::string

I am swimming in deep waters here, just looking for a bit of guidance.

Windoze info

/*
g++ -std=gnu++11  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG   -I"C:/Users/......./AppData/Local/R/WIN-LI~1/4.2/Rcpp/include" -I"C:/_git_/github/......./src" -I"C:/_git_/github/......./inst/include"   -I"C:/rtools42/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -mfpmath=sse -msse2 -mstackrealign  -c base64.cpp -o base64.o


R_RTOOLS42_PATH                             
C:\rtools42/x86_64-w64-mingw32.static.posix/bin;C:\rtools42/usr/bin

"pkg.version(Rcpp)"
[1] ‘1.0.9’


> R.version
               _                                
platform       x86_64-w64-mingw32               
arch           x86_64                           
os             mingw32                          
crt            ucrt                             
system         x86_64, mingw32                  
status                                          
major          4                                
minor          2.1                              
year           2022                             
month          06                               
day            23                               
svn rev        82513                            
language       R                                
version.string R version 4.2.1 (2022-06-23 ucrt)
nickname       Funny-Looking Kid  
*/

Dirk's answer

> r = (charToRaw("The quick brown fox"))
> r
 [1] 54 68 65 20 71 75 69 63 6b 20 62 72 6f 77 6e 20 66 6f 78
> r2c(r)
[1] "The quick brown fox"

> r2c(charToRaw("The quick brown fox"))
[1] "The quick brown fox\xd2\xce\002"

### BAFFLING ### Windoze!?<!?

> r <- charToRaw("The quick brown fox")
> r2c(r)
[1] "The quick brown fox\xdb\xce\002"
> r = (charToRaw("The quick brown fox"))
> r2c(r)
[1] "The quick brown fox"


1 Answers

As hinted in the comments, the answer is hidden away in the RcppRedis package from which I just borrowed this actual one-liner (which I broke up onto three lines for nice display here):

> Rcpp::cppFunction("std::string r2c(RawVector x) { \
       const char *c = reinterpret_cast<char*>(x.begin()); \
       return std::string(c); }")
> r <- charToRaw("The quick brown fox")
> r
 [1] 54 68 65 20 71 75 69 63 6b 20 62 72 6f 77 6e 20 66 6f 78
> r2c(r)
[1] "The quick brown fox"
> 

We basically just ask C++ to 'view' the raw chars as standard chars. There is likely also a C function in R itself you could borrow. This worked for me, and apparently since at least 2014.

Related