crackcell's dustbin home
首页 > R环境的C扩展的简易示例 > 正文

R环境的C扩展的简易示例

/* -*- author: Tan Menglong; email: tanmenglong_at_gmail; twitter/weibo: @crackcell; 转载请注明出处 -*- */

1 C写R扩展的限制

  1. 被R调用的C函数必须返回void,要使用返回值,需要通过参数传递返回值指针
  2. 所有传递给C函数的参数都是指针
  3. 需要包含头文件R.h

2 宇宙惯例:hello world

  1. C代码,hello.c
#include <R.h>

void hello(const char **msg) {
    Rprintf("msg from R: %s", *msg);
}
  1. 编译,生成hello.so
R CMD SHLIB hello.c
  1. 进入R环境,调用加载so并调用函数
> dyn.load('hello.so')
> .C("hello", as.character("hello world"))
msg from R: hello world[[1]]
[1] "hello world"

3 示例2

这个例子是带返回值的。

  1. C代码
#include <R.h>

void plus(const int *a, const int *b, int *result) {
    *result = *a + *b;
}
  1. 在R中调用
> dyn.load('hello.so')
> .C("plus", as.integer(1), as.integer(2), as.integer(0))[[3]]
[1] 3

注意,这里传参的时候,第3个返回值的参数也需要传。.C函数返回一个列表,列表的每个项保存参数的值。这里,使用的是第3个,也就是result。

4 了解更多

Author: Menglong Tan <tanmenglong AT gmail DOT com>

Date: 2012-04-04 16:29:34 CST

HTML generated by org-mode 6.33x in emacs 23

分享到:

blog comments powered by Disqus

Modified theme and code from Tom Preston-Werner. Hosted by Baidu App Engine.