本文介绍了怎样的R字符向量转换成一个C字符指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图从研发传递一个特征向量为C,并通过一个C字符指针引用它。但是,我不知道用哪个类型转换宏。下面是一个小的测试说明我的问题。
I'm trying to pass a character vector from R to C and reference it through a C character pointer. However, I don't know which type conversion macro to use. Below is a small test illustrating my problem.
文件test.c的:
#include <Rinternals.h>
SEXP test(SEXP chars)
{
char *s;
s = CHAR(chars);
return R_NilValue;
}
文件test.R:
File test.R:
dyn.load("test.so")
chars <- c("A", "B")
.Call("test", chars)
从R输出:
> source("test.R")
Error in eval(expr, envir, enclos) :
CHAR() can only be applied to a 'CHARSXP', not a 'character'
任何线索?
推荐答案
在字符串的字符的可以通过获取每个字符通过指针 CHAR(STRING_ELT(字符进行检索,我)
,其中0℃=的 I 的&LT;长度(字),并将其存储在 S [I]
。
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;
}
这篇关于怎样的R字符向量转换成一个C字符指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!