如何从研发调用C函数? [英] How to call C function from R?
问题描述
您如何使用从,使用R数据R级C语言编写的一些功能。
例如。使用像功能:
双* addOneToVector(INT N,常量双*向量){
双* ANS =的malloc(sizeof的(双)* N);
的for(int i = 0; I< N ++ I)
答[我] =向量[I] + 1
返回答;
}
在上下文:
X = 1:3
X = addOneToVector(X)
X#2,3,4
我搜索计算器第一,但我注意到,没有答案,在这里。结果
总的想法是(对于Linux命令,但可以在其他操作系统一样的想法):
-
创建功能,将只需要指向基本类型,做受副作用(返回void)的一切。例如:
无效addOneToVector为(int * N,双*向量){
的for(int i = 0; I< * N; ++ I)
矢量[I] + = 1.0;
} -
编译文件C源作为动态库,均可以使用快捷方式来做到这一点:
$ R CMD SHLIB lib.c
-
从研发加载动态库:
dyn.load(foo.so)
-
使用
.C
R函数调用C函数,例如:X = 1:3
RET_VAL = .C(addOneToVector,N =长度(X),矢量= as.double(X))
它返回列表,从中可以调用函数如后得到的输入值。
RET_VAL $ X#2,3,4
您现在可以包装它要能够从研发更容易使用。
有一个很好的页面描述在这里与更多的细节全过程(也包括Fortran语言):
http://users.stat.umn.edu/~geyer/rc/
How can you use some function written in C from R level using R data. eg. to use function like:
double* addOneToVector(int n, const double* vector) {
double* ans = malloc(sizeof(double)*n);
for (int i = 0; i < n; ++i)
ans[i] = vector[i] + 1
return ans;
}
in the context:
x = 1:3
x = addOneToVector(x)
x # 2, 3, 4
I've searched stackoverflow first but I noticed there is no answer for that in here.
The general idea is (commands for linux, but same idea under other OS):
Create function that will only take pointers to basic types and do everything by side-effects (returns void). eg:
void addOneToVector(int* n, double* vector) { for (int i = 0; i < *n; ++i) vector[i] += 1.0; }
Compile file C source as dynamic library, you can use R shortcut to do this:
$ R CMD SHLIB lib.c
Load dynamic library from R:
dyn.load("foo.so")
Call C functions using
.C
R function, IE:x = 1:3 ret_val = .C("addOneToVector", n=length(x), vector=as.double(x))
It returns list from which you can get value of inputs after calling functions eg.
ret_val$x # 2, 3, 4
You can now wrap it to be able to use it from R easier.
There is a nice page describing whole process with more details here (also covering Fortran):
http://users.stat.umn.edu/~geyer/rc/
这篇关于如何从研发调用C函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!