How do I convert an R character vector to a C character pointer?

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

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

See the Handling Character Data section of Writing R Extensions. Dirk will be along shortly to tell you how this all will be easier if you just use C++ and Rcpp. :)


As per 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 are zero-offset, so 1 picks the second element.


The string in chars can be retrieved by getting each character through the pointer CHAR(STRING_ELT(chars, i)), where 0 <= i < length(chars), and storing 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;
}

Tags:

C

R