Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call C function from R?

Tags:

c

r

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
like image 923
Yester Avatar asked Jun 16 '26 03:06

Yester


1 Answers

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):

  1. Create function that will only take pointers to basic types and do everything by side-effects (returns void). eg in a file called foo.c:

    void addOneToVector(int* n, double* vector) {
        for (int i = 0; i < *n; ++i)
            vector[i] += 1.0;
    }
    
  2. Compile file C source as dynamic library, you can use R shortcut to do this:

    $ R CMD SHLIB foo.c
    

    This will then create a file called foo.so on Mac or foo.dll on Windows.

  3. Load dynamic library from R

    on Mac:

    dyn.load("foo.so")
    

    or on Windows:

    dyn.load("foo.dll")
    
  4. 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/

like image 163
Yester Avatar answered Jun 17 '26 20:06

Yester



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!