处理从R到C的列表并访问它
我想在C中使用一个列表,我从R得到了。我意识到问题与此非常类似: 使用.call()将dataframe从-R传递到R和C. 但是,我无法将其存储在指针“* target”中,我将从中进一步使用它。
R:
.Call("processlist", list(c(1,2), c(1,3,2), c(1,5,4,4)))
在C:
#include #include extern "C" { SEXP processlist(SEXP lst); } SEXP processlist(SEXP lst){ SEXP vec = PROTECT(allocVector(VECSXP, 2)); SET_VECTOR_ELT(vec, 0, VECTOR_ELT(c, 0); SET_VECTOR_ELT(vec, 1, VECTOR_ELT(c, 1); SET_VECTOR_ELT(vec, 2, VECTOR_ELT(c, 2); const lngth = 3; int *target[lnght]; // Here i want to fill "target", but how? int *preTarget = INTEGER(vec); // Bad attempts target[0] = INTEGER(preTarget[0]); target[0] = INTEGER(vec[0]); }
注意:遗憾的是,C ++不是一个选项。
编辑:所需的输出将是我可以通过以下方式调用*目标。
target[0][0] --> Returns: 1 target[1][2] --> Returns: 2 target[2][3] --> Returns: 4
以这种方式调用“vec”会让我错误。
在我看来,您只想从C侧访问列表中的值。 如果这是正确的,请查看下面的代码。
在dc
:
/* Including some headers to show the results*/ #include #include #include #include #include SEXP processlist(SEXP lst){ int i,l = length(lst); /* You need an array of arrays, so target will be an int** */ int **target = malloc(sizeof(int *)*l); for (i=0;i
需要注意的重要一点是target
必须是int**
,因为它是指向指针数组的指针。
在dR
(在编译dc
之后):
dyn.load("d.so") mylist<-list(c(1,2), c(1,3,2), c(1,5,4,4)) #This is very important: by default 1 in R is double. #You need to coerce every element of the list to integer. mylist<-lapply(mylist,as.integer) .Call("processlist", mylist)
请注意,我们需要将列表的每个元素强制转换为整数。 以上产生:
target[0][0]: 1 target[1][2]: 2 target[2][3]: 4