How to call C function from R?

后端 未结 3 2013
梦毁少年i
梦毁少年i 2020-12-09 06:45

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) {
    dou         


        
3条回答
  •  独厮守ぢ
    2020-12-09 07:24

    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:

      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 lib.c
      
    3. Load dynamic library from R:

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

提交回复
热议问题