首页 > 代码库 > R调用C语言简单实例

R调用C语言简单实例

新建目录C:/D_package/work_source/R_work/convolve,并创建convolve.c 文件

打开R(32bit,64bit的会报错和安装环境有关)

> setwd(‘C:/D_package/work_source/R_work/convolve‘)

> system("R CMD SHLIB convolve.c")
gcc -m32 -I"C:/PROGRA~1/R/R-31~1.2/include" -DNDEBUG     -I"d:/RCompile/CRANpkg/extralibs64/local/include"     -O3 -Wall  -std=gnu99 -mtune=core2 -c convolve.c -o convolve.o
gcc -m32 -shared -s -static-libgcc -o convolve.dll tmp.def convolve.o -Ld:/RCompile/CRANpkg/extralibs64/local/lib/i386 -Ld:/RCompile/CRANpkg/extralibs64/local/lib -LC:/PROGRA~1/R/R-31~1.2/bin/i386 -lR
> # 生成了两个文件convolve.dll和convolve.o
> # convolve.dll用于windows上
> dyn.load("convolve.dll") #导入dll文件
>  #调用 convolve方法 即convolve.c中的方法convolve
> conv <- function(a,b){
+ .C("convolve",
+ as.double(a),as.integer(length(a)),
+ as.double(b),as.integer(length(b)),
+ ab = double(length(a)+length(b)-1))$ab
+ }
> a=3
> b=4
> conv(a,b)
[1] 12
> b=6
> conv(a,b)
[1] 18


R调用C语言简单实例