如何将R字符向量转换为C字符指针?

Aug*_*rom 8 c r

我正在尝试将字符向量从R传递给C并通过C字符指针引用它.但是,我不知道要使用哪种类型的转换宏.下面是一个小测试,说明了我的问题.

文件test.c:

#include <Rinternals.h>

SEXP test(SEXP chars)
{
   char *s;

   s = CHAR(chars);
   return R_NilValue;
}
Run Code Online (Sandbox Code Playgroud)

文件测试.R:

dyn.load("test.so")

chars <- c("A", "B")

.Call("test", chars)
Run Code Online (Sandbox Code Playgroud)

R的输出:

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

有线索吗?

Jos*_*ich 8

字符向量是STRSXP.每个元素都是CHARSXP,所以你需要像(未经测试的):

const char *s;
s = CHAR(STRING_ELT(chars, 0));
Run Code Online (Sandbox Code Playgroud)

请参阅编写R扩展处理字符数据部分.如果您只使用C++和Rcpp,Dirk将很快告诉您这一切将如何变得更容易.:)


Aug*_*rom 7

可以通过指针获取每个字符来检索chars 中的字符串CHAR(STRING_ELT(chars, i)),其中 0 <= i < length(chars),并将其存储在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;
}
Run Code Online (Sandbox Code Playgroud)