[英]How do I convert an R character vector to a C character pointer?
I'm trying to pass a character vector from R to C and reference it through a C character pointer. 我正在尝试将字符向量从R传递给C并通过C字符指针引用它。 However, I don't know which type conversion macro to use. 但是,我不知道要使用哪种类型的转换宏。 Below is a small test illustrating my problem. 下面是一个小测试,说明了我的问题。
File test.c: 文件test.c:
#include <Rinternals.h>
SEXP test(SEXP chars)
{
char *s;
s = CHAR(chars);
return R_NilValue;
}
File test.R: 文件测试.R:
dyn.load("test.so")
chars <- c("A", "B")
.Call("test", chars)
Output from R: R的输出:
> source("test.R")
Error in eval(expr, envir, enclos) :
CHAR() can only be applied to a 'CHARSXP', not a 'character'
Any clues? 有线索吗?
Character vectors are STRSXP
. 字符向量是STRSXP
。 Each individual element is CHARSXP
, so you need something like (untested): 每个元素都是CHARSXP
,所以你需要像(未经测试的):
const char *s;
s = CHAR(STRING_ELT(chars, 0));
See the Handling Character Data section of Writing R Extensions . 请参阅编写R扩展的处理字符数据部分 。 Dirk will be along shortly to tell you how this all will be easier if you just use C++ and Rcpp. 如果您只使用C ++和Rcpp,Dirk将很快告诉您这一切将如何变得更容易。 :) :)
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]
. 可以通过使每个字符通过指针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;
}
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. C向量是零偏移,因此1选择第二个元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.