[Rcpp-devel] Understanding the behaviour of const CharacterVector as a function parameter

Romain Francois romain at r-enthusiasts.com
Sun Sep 29 17:26:42 CEST 2013


Hello,

What acts as a proxy for const CharacterVector& does not do its proxy 
job. Instead it gives direct access to the underlying array of SEXP that 
character vector use.

This has been fixed in Rcpp11. The relevant addition is the 
const_string_proxy class. See this commit which can easily be applied to 
Rcpp. 
https://github.com/romainfrancois/Rcpp11/commit/f5e1600f7acbf3bef39325c06ef3ac5ddf8dc66a

The commit in Rcpp11 also has removed a few things from the proxy class 
that I don't judge needed anymore because I'm cleaning things. This 
might not apply to Rcpp with its more strict compatibility requirements.

Romain

Le 29/09/13 15:24, Romain Francois a écrit :
> Le 29/09/13 14:06, Simon Zehnder a écrit :
>> Dear Rcpp::Users and Rcpp::Devels,
>>
>> I would like to understand a certain behaviour of my code I
>> encountered lately.
>>
>> I am working with CharacterVector and the following behaviour occurred:
>>
>> void test1 (Rcpp::CharacterVector &charv)
>> {
>>     Rprintf("test1: %s\n", (char*) charv(0));
>> }
>>
>> void test2 (const Rcpp::CharacterVector &str)
>> {
>>     Rprintf("test2: %s\n", (char*) charv(0));
>> }
>
> Try actually using the variable you pass in, as in:
>
> void test2 (const Rcpp::CharacterVector &str)
> {
>      Rprintf("test2: %s\n", (char*) str(0));
> }
>
> Although it still exposes the bug.
>
> You can use something like this in the meantime:
>
> void test2 (const Rcpp::CharacterVector& charv)
> {
>      String x = charv[0] ;
>      Rprintf("test2: %s\n", x.get_cstring());
> }
>
> It looks like the bug is about converting the result of charv(0) to a
> char*. Probably worth looking at the string_proxy class.
>
> Romain
>
>> Using a string like "2013-05-04 20:23:21" for the
>> Rcpp::CharacterVector gives the following outputs:
>>
>> test1: 2013-05-04 20:23:21
>>
>> test2:  `
>>
>> This does also not change if I use a cast to const char* in test2. I
>> tried something similar with strings and printing the c_str() of them,
>> there the 'const' keyword does not make a difference - it always
>> prints the correct string.
>>
>> Is this something specific to the Rcpp::CharacterVector, that uses a
>> string_proxy for its elements returned by the operator ()? Is there a
>> way to use const Rcpp::CharacterVector and get the behaviour of test1?
>>
>>
>> Best
>>
>> Simon
>


-- 
Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30



More information about the Rcpp-devel mailing list