How to convert character vector R to character pointer C?

I am trying to pass a character vector from R to C and refer to it with the character C. However, I do not know which type conversion macro to use. Below is a small test illustrating my problem.

File test.c:

#include <Rinternals.h> SEXP test(SEXP chars) { char *s; s = CHAR(chars); return R_NilValue; } 

File test.R:

 dyn.load("test.so") chars <- c("A", "B") .Call("test", chars) 

Exit R:

 > source("test.R") Error in eval(expr, envir, enclos) : CHAR() can only be applied to a 'CHARSXP', not a 'character' 

Any clues?

+6
source share
3 answers

The string in characters can be obtained by entering each character through the CHAR(STRING_ELT(chars, i) pointer CHAR(STRING_ELT(chars, i) , where 0 <= i <(characters) and save it in s[i] .

 #include <stdlib.h> #include <Rinternals.h> SEXP test(SEXP chars) { int n, i; char *s; n = length(chars); s = malloc(n + 1); if (s != NULL) { for (i = 0; i < n; i++) { s[i] = *CHAR(STRING_ELT(chars, i)); } s[n] = '\0'; } else { /*handle malloc failure*/ } return R_NilValue; } 
+4
source

Character vectors STRSXP . Each individual element is CHARSXP , so you need something like (untested):

 const char *s; s = CHAR(STRING_ELT(chars, 0)); 

See the section "Character Handling" in the "Writing Extensions" section . Soon you will set off to tell you how all this will be easier if you just use C ++ and Rcpp. :)

+6
source

According to Josh's request:

 R> pickString <- cppFunction('std::string pickString(std::vector<std::string> invec, int pos) { return invec[pos]; } ') R> pickString(c("The", "quick", "brown", "fox"), 1) [1] "quick" R> 

C vectors have zero bias, so 1 selects the second element.

+2
source

All Articles